Skip to content

Commit 36e944e

Browse files
added Roman to Integer Solution in String Problems
1 parent 332a5c0 commit 36e944e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Topic/Solution/romanToInt.java

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

0 commit comments

Comments
 (0)