Roman to Integer

Monisha Mathew
1 min readMar 10, 2019

--

Question: Given String value of a Roman numeral, compute and return the integer equivalent. Find the full question here.

Approach 1: As usual let’s start with the simplest solution —

class Solution {
//Runtime: 36ms
//Memory usage: 39MB
Map<Character, Integer> map = new HashMap();

private void setMap(){
map = new HashMap();
map.put(‘I’, 1);
map.put(‘V’, 5);
map.put(‘X’, 10);
map.put(‘L’, 50);
map.put(‘C’, 100);
map.put(‘D’, 500);
map.put(‘M’, 1000);
}
public int romanToInt(String s) {
setMap();
char[] roman = s.toCharArray();
int finalInt = 0;
for(int i = 0; i<roman.length-1; i++) {
if(map.get(roman[i])>=map.get(roman[i+1])) {
finalInt+=map.get(roman[i]);
}else {
finalInt-=map.get(roman[i]);
}
}
return finalInt+map.get(roman[roman.length-1]);
}
}

Using a HashMap for lookup and following the instructions in the question was the easiest way to tackle the problem. There’s definitely a lot of scope for improvement, which we’ll look at in a future post shared here. Until then…

Find more posts here.

Cheers & Chao!

--

--