Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
int romanToInt(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
map<char, int> symbols;
symbols.clear();
symbols[' '] = 0;
symbols['I'] = 1;
symbols['V'] = 5;
symbols['X'] = 10;
symbols['L'] = 50;
symbols['C'] = 100;
symbols['D'] = 500;
symbols['M'] = 1000;
int length = s.size();
char currentSymbol;
char previousSymbol = ' ';
int solution = 0;
int digit = 0;
for (int i=0;i<length;++i){
currentSymbol = s[i];
if (currentSymbol!=previousSymbol){
if (symbols[previousSymbol]<symbols[currentSymbol]){
solution += -digit;
digit = symbols[currentSymbol];
previousSymbol = currentSymbol;
}
else if (symbols[previousSymbol]>symbols[currentSymbol]){
solution += digit;
digit = symbols[currentSymbol];
previousSymbol = currentSymbol;
}
}
else{// symbol == currentSymbol
digit += symbols[currentSymbol];
}
if (i==length-1)
solution += digit;
}
return solution;
}
};