Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
» Solve this problem
同Integer To Roman一题一样,建立常数表,直接处理。
class Solution {
public:
const string romans[4][10] = {
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "M", "MM", "MMM", "", "", "", "", "", ""}
};
int romanToInt(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int ans = 0, power = 1000;
int head = 0, idx = 3;
string temp;
while (head < s.size()) {
for (int i = 9; i >= 1; i--) {
int length = romans[idx][i].size();
if (length != 0 && head + length <= s.size()) {
temp = s.substr(head, length);
if (temp == romans[idx][i]) {
ans += i * power;
head += length;
break;
}
}
}
idx--;
power /= 10;
}
return ans;
}
};