Roman to Integer Cont(2)…
1 min readMar 29, 2019
Question: Given String value of a Roman numeral, compute and return the integer equivalent. Find the full question here.
And in case you are just starting off, you might want to take a look at the initial approach posted here and may be here.
Approach 3: Well, we are borrowing the fundamental ideas from the previous approaches of course. But we are trying to implement the lookup in a different way. This is definitely boosting our run-time by leaps and bounds. The look up is implemented using static map with a static anonymous block for initialization.
Let’s dive into the code straight away —
//Approach 3
//Runtime: 4ms
//Memory usage: 37.2MBclass Solution {
private static HashMap<Character, Integer> map = new HashMap<>();
static {
map.put('M', 1000);
map.put('D', 500);
map.put('C', 100);
map.put('L', 50);
map.put('X', 10);
map.put('V', 5);
map.put('I', 1);
}
public int romanToInt(String s) {
char[] roman = s.toCharArray();
int finalInt = 0;
int curr = map.get(roman[0]);
int next = 0;
for(int i = 0; i<roman.length-1; i++) {
next =map.get(roman[i+1]);
if(curr>=next) {
finalInt+=curr;
}else {
finalInt-=curr;
}
curr = next;
}
return finalInt+curr;
}
}
Find more posts here.
Cheers & Chao!