Skip to content

Commit 98c68b3

Browse files
author
Prakhar Agarwal
authored
Create Roman to Integer.java
1 parent 06491f6 commit 98c68b3

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Roman to Integer.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
public class Solution {
2+
public int romanToInt(String s) {
3+
Map<Character, Integer> map = new HashMap<>();
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+
char[] chars = s.toCharArray();
12+
int result = 0;
13+
int i = 0, j = 1;
14+
for (; j < chars.length; i++, j++) {
15+
if (map.get(chars[i]) >= map.get(chars[j])) {
16+
result += map.get(chars[i]);
17+
} else {
18+
result -= map.get(chars[i]);
19+
}
20+
}
21+
result += map.get(chars[i]);
22+
return result;
23+
}
24+
}

0 commit comments

Comments
 (0)