-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroman to integer.java
40 lines (36 loc) · 1021 Bytes
/
roman to integer.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
30
31
32
33
34
35
36
37
38
39
40
/*Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3. */
class Solution {
public int romanToInt(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
int sum = 0;
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);
s = s.replace("IV", "IIII");
s = s.replace("IX", "VIIII");
s = s.replace("XL", "XXXX");
s = s.replace("XC", "LXXXX");
s = s.replace("CD", "CCCC");
s = s.replace("CM", "DCCCC");
for (int i = 0; i < s.length(); i++) {
sum = sum + (map.get(s.charAt(i)));
}
return sum;
}
}