一、C++代碼:
int romanToInt(string s) {
int res = 0;
map<char, int> mapRoman = { {'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000} };
while (s.size() > 0) {
char temp = s.back();
int num1 = mapRoman.find(temp)->second;
s.pop_back();
if (s.size() > 0) {
char temp1 = s.back();
int num2 = mapRoman.find(temp1)->second;
if (num1 / num2 == 5 || num1 / num2 == 10 && num1%num2 == 0) {
res += num1 - num2;
s.pop_back();
}
else {
res += num1;
}
}
else {
res += num1;
}
}
return res;
}