-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoman2Int.java
More file actions
53 lines (44 loc) · 1.21 KB
/
Copy pathRoman2Int.java
File metadata and controls
53 lines (44 loc) · 1.21 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
package roman2Int;
import java.util.HashMap;
import java.util.Map;
public class Roman2Int {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "MCMXCIV";
int result = roman2Int(s);
System.out.println("result: " + result);
}
public static int roman2Int(String s) {
Map<Character, Integer> symbolMap = new HashMap<Character, Integer>();
symbolMap.put('I', 1);
symbolMap.put('V', 5);
symbolMap.put('X', 10);
symbolMap.put('L', 50);
symbolMap.put('C', 100);
symbolMap.put('D', 500);
symbolMap.put('M', 1000);
int result = 0;
int curr = 0;
if (s.length() == 0)
return 0;
if (s.length() == 1) {
return symbolMap.get(s.charAt(0));
} else {
while (curr <= s.length()-2) {
//check if subtraction is needed on s[0] and s[1]
if (symbolMap.get(s.charAt(curr)) < symbolMap.get(s.charAt(curr+1))) {
result = result +
symbolMap.get(s.charAt(curr+1)) - symbolMap.get(s.charAt(curr));
curr = curr + 2;
} else {
result = result +
symbolMap.get(s.charAt(curr));
curr = curr + 1;
}
}
if (curr == s.length()-1)
result = result + symbolMap.get(s.charAt(s.length()-1));
}
return result;
}
}