Problem Statement
Pattern:
Solution
public int value (char ch) {
switch (ch) {
case 'I' : return 1;
case 'V' : return 5;
case 'X' : return 10;
case 'L' : return 50;
case 'C' : return 100;
case 'D' : return 500;
default : return 1000;
}
}
public int romanToInt(String s) {
int prev = -1, sum = 0;
for (char ch : s.toCharArray()) {
int curr = value(ch);
sum+= curr;
if(prev != -1 && prev < curr ) sum -= 2*prev;
prev = curr;
}
return sum;
}
TC : SC :
Notes
- if a smaller number comes before a larger number, instead of adding it to the sum, we subtract it from the sum.