Leetcode 13. Roman to Integer (Easy) (cpp)
Tag: Math, String
Difficulty: Easy
/*
13. Roman to Integer (Easy)
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) {
int num = ChatoNum(s[0]);
for (int i = 1; i < s.length(); i++) {
if (ChatoNum(s[i]) > ChatoNum(s[i - 1])) {
num += ChatoNum(s[i]) - 2 * ChatoNum(s[i - 1]);
} else {
num += ChatoNum(s[i]);
}
}
return num;
}
int ChatoNum(char cha) {
switch (cha) {
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;
}
return 0;
}
};