Skip to content

Commit 0e76415

Browse files
authoredMar 14, 2017
Create 13. Roman to Integer
1 parent 1cb4199 commit 0e76415

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
 

‎13. Roman to Integer

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
public class Solution {
2+
public int romanToInt(String s) {
3+
HashMap <Character,Integer> map = new HashMap <Character, Integer>();
4+
map.put('I',1);
5+
map.put('V',5);
6+
map.put('X',10);
7+
map.put('L',50);
8+
map.put('C',100);
9+
map.put('D',500);
10+
map.put('M',1000);
11+
// MMDC 2000 + 500 + 100
12+
// MMCD 2000 - 100 + 500
13+
14+
int len = s.length();
15+
int result = map.get(s.charAt(len - 1));
16+
for(int i = len - 2; i >= 0; i--){
17+
if(map.get(s.charAt(i+1))<= map.get(s.charAt(i))){
18+
result += map.get(s.charAt(i));
19+
}else{
20+
result -= map.get(s.charAt(i));
21+
}
22+
}
23+
return result;
24+
}
25+
}

0 commit comments

Comments
 (0)