Leetcode 13. Roman to Integer
Description:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Thinking:
We may find from the chart that:
I
should be followed by oneV/X
(sum >= 5) or severalI
(sum < 5);X
should be followed by oneL/C/D/M
(sum >= 50) or severalI/X
(sum < 50);C
should be followed by oneD/M
(sum >= 500) or severalI/X/L/C
(sum < 500);
Steps:
- Check whether input is valid;
- Start from the end of the String, check each character and use switch-case structure.
- When character is
I, X, C
, we should check the result we already got to decide whether we need to add or subtract.
Code:
public class Solution {
public int romanToInt(String s) {
if(s.isEmpty()) return -1;
int result = 0;
for(int i = s.length()-1; i >=0; i--){
char roman = s.charAt(i);
switch(roman){
case 'I':
result += result >= 5 ? -1 : 1;
break;
case 'V':
result += 5;
break;
case 'X':
result += result >= 50 ? -10 : 10;
break;
case 'L':
result += 50;
break;
case 'C':
result += result >= 500 ? -100 : 100;
break;
case 'D':
result += 500;
break;
case 'M':
result += 1000;
break;
//Also can add default:break;
}
}
return result;
}
}
Conclusion:
Trying to look for some patterns and rules is one of the best way to solve the problem of string.