Leetcode#13 Roman to Integer
Published:
Idea:
naive
Solution:
class Solution {
public:
int romanToInt(string s) {
int num = 0;
int i=0;
while(i<s.size()){
char c = s[i];
if(c == 'M') {
num += 1000;
i++;
} else if (c == 'C' && i < s.size()-1 && s[i+1] == 'M') {
num += 900;
i += 2;
} else if (c == 'D') {
num += 500;
i++;
} else if (c == 'C' && i < s.size()-1 && s[i+1] == 'D') {
num += 400;
i += 2;
} else if (c == 'C') {
num += 100;
i++;
} else if (c == 'X' && i < s.size()-1 && s[i+1] == 'C') {
num += 90;
i += 2;
} else if (c == 'L') {
num += 50;
i++;
} else if (c == 'X' && i < s.size()-1 && s[i+1] == 'L') {
num += 40;
i += 2;
} else if (c == 'X') {
num += 10;
i++;
} else if (c == 'I' && i < s.size()-1 && s[i+1] == 'X') {
num += 9;
i += 2;
} else if (c == 'V') {
num += 5;
i++;
} else if (c == 'I' && i < s.size()-1 && s[i+1] == 'V') {
num += 4;
i += 2;
} else {
num += 1;
i++;
}
}
return num;
}
};