13. Roman to Integer
We assume that the input is a valid roman number (very important). Given a valid roman number, if a pair of integers of two roman characters is strictly ascending, minus the previous integer in the pair, otherwise plus it.
class Solution {
public int romanToInt(String s) {
int sum = 0;
int prev = getNumber(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
int curr = getNumber(s.charAt(i));
if (prev < curr) {
sum -= prev;
} else {
sum += prev;
}
prev = curr;
}
sum += prev;
return sum;
}
private int getNumber(char c) {
switch (c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
}