Roman to Integer Cont…

Monisha Mathew
1 min readMar 11, 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.

Approach 2:

//Approach 2
//RunTime: 32ms
//Memory usage: 38.9MB
class Solution {

private int getInt(char c){
if(c=='M') return 1000;
else if(c=='D') return 500;
else if(c=='C') return 100;
else if(c=='L') return 50;
else if(c=='X') return 10;
else if(c=='V') return 5;
else if(c=='I') return 1;
return 0;
}
public int romanToInt(String s) {
char[] roman = s.toCharArray();
int finalInt = 0;
int curr = getInt(roman[0]);
int next = 0;
for(int i = 0; i<roman.length-1; i++) {
next =getInt(roman[i+1]);
if(curr>=next) {
finalInt+=curr;
}else {
finalInt-=curr;
}
curr = next;
}
return finalInt+curr;
}
}

Key Take Away:

  • Maps are effective only when the search is within a large or a growing collection. In our case, the search is always within a fixed small set and therefore, a simple if-else ladder will be more effective and faster.
  • The use of an extra array to hold the individual characters is a trade off between space and speed. String’s charAt() method can significantly slow down the fetch compared to a simple read operation on an array.
  • Using String’s ‘length()’ method takes longer array’s ‘length’. A method call always takes longer than a member variable look-up.

Looks like there is still room for improvement in the code quality. Still exploring. Until next time…

Find more posts here.

Cheers & Chao!

--

--