LeetCode第13题,给定一个罗马数字,将他转换为整形
AC代码
class Solution {
public:
int romanToInt(string s) {
int result = 0,num = 0,pre = INT_MAX;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == 'I') num = 1;
else if(s[i] == 'X') num = 10;
else if(s[i] == 'C') num = 100;
else if(s[i] == 'M') num = 1000;
else if(s[i] == 'V') num = 5;
else if(s[i] == 'L') num = 50;
else if(s[i] == 'D') num = 500;
//乘以2是因为开始已经把左边的数加上了
if(pre < num) result = result + num - 2 * pre;
else result = result + num;
pre = num;
}
return result;
}
};