forked from kdn251/interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRomanToInteger.java
More file actions
31 lines (24 loc) · 841 Bytes
/
RomanToInteger.java
File metadata and controls
31 lines (24 loc) · 841 Bytes
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
// Given a roman numeral, convert it to an integer.
// Input is guaranteed to be within the range from 1 to 3999
public class RomanToInteger {
public int romanToInt(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
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 total = 0;
for(int i = 0; i < s.length() - 1; i++) {
if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
total -= map.get(s.charAt(i));
} else {
total += map.get(s.charAt(i));
}
}
total += map.get(s.charAt(s.length() - 1));
return total;
}
}