forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
29 lines (29 loc) · 844 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public int romanToInt(String s) {
Map<String, Integer> nums = new HashMap<>();
nums.put("M", 1000);
nums.put("CM", 900);
nums.put("D", 500);
nums.put("CD", 400);
nums.put("C", 100);
nums.put("XC", 90);
nums.put("L", 50);
nums.put("XL", 40);
nums.put("X", 10);
nums.put("IX", 9);
nums.put("V", 5);
nums.put("IV", 4);
nums.put("I", 1);
int res = 0;
for (int i = 0; i < s.length();) {
if (i + 1 < s.length() && nums.get(s.substring(i, i + 2)) != null) {
res += nums.get(s.substring(i, i + 2));
i += 2;
} else {
res += nums.get(s.substring(i, i + 1));
i += 1;
}
}
return res;
}
}