Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

罗马数字转整数

题目

lettcode-13题
难度:简单
This is a picture without description

解题思路

对于每个罗马符号所对应的数值,我们可以将其用一个HashMap存起来,将其字符作为key,以及数值为相应的value

在方法中对输入的字符串的所有字符进行遍历,get到所对应的值,并拿到它的后一位数的值,如果当前符号的值大于后一位符号的值,则进行+运算,否则-运算。

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//leetcode项目
class Solution {
Map<Character,Integer> map=new HashMap<Character,Integer>();
public int romanToInt(String s) {
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);
int ans = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
int value = map.get(s.charAt(i));
if (i < n - 1 && value < map.get(s.charAt(i + 1))) {
ans -= value;
} else {
ans += value;
}
}
return ans;
}
}