13 Roman to Integer
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) {
/*
I V X L C D M
1 5 10 50 100 500 1000
*/
int res = 0;
int i = 0, n = s.size();
while ( i <= n-1 ) {
char c1 = s[i], c2 = ' ';
if ( i <= n-2 ) c2 = s[i+1];
if ( c1 == 'M' ) res += 1000;
if ( c1 == 'D' ) res += 500;
if ( c1 == 'C' ) {
if ( c2 == 'D') {res += 400; i += 1;}
if ( c2 == 'M') {res += 900; i += 1;}
if ( c2 != 'D' and c2 != 'M' ) res += 100;
}
if ( c1 == 'L' ) res += 50;
if ( c1 == 'X' ) {
if ( c2 == 'L') {res += 40; i += 1;}
if ( c2 == 'C') {res += 90; i += 1;}
if ( c2 != 'L' and c2 != 'C' ) res += 10;
}
if ( c1 == 'V' ) res += 5;
if ( c1 == 'I' ) {
if ( c2 == 'V') {res += 4; i += 1;}
if ( c2 == 'X') {res += 9; i += 1;}
if ( c2 != 'V' and c2 != 'X' ) res += 1;
}
i += 1;
}
return res;
}
};
Note: it is illegal to define an empty character:
char c = '';