forked from ganjingcatherine/Lintcode_HighFreq
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path419.roman-to-integer.java
More file actions
39 lines (35 loc) · 902 Bytes
/
419.roman-to-integer.java
File metadata and controls
39 lines (35 loc) · 902 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
32
33
34
35
36
37
38
39
public class Solution {
/*
* @param s: Roman representation
* @return: an integer
*/
private Map<Character, Integer> dict;
public Solution() {
// https://en.wikipedia.org/wiki/Roman_numerals
dict = new HashMap<>();
dict.put('I', 1);
dict.put('V', 5);
dict.put('X', 10);
dict.put('L', 50);
dict.put('C', 100);
dict.put('D', 500);
dict.put('M', 1000);
}
public int romanToInt(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] sc = s.toCharArray();
int prev = 0;
int ans = 0;
for (char c : sc) {
int cur = dict.get(c);
ans += cur;
if (prev < cur) {
ans -= 2*prev;
}
prev = cur;
}
return ans;
}
}