解题思路
首先初始化一个map,设置罗马数字对应的值,当遇到IX这类情况,较小的值在较大的值左边,则代表的是10 (X) - 1(I) = 9。遇到III或XI,即左边的值大于等于右边的值这种情况则直接相加。用preNum存储上一个遇到的罗马数字的值便于比较。
代码
#include<map>
class Solution {
public:int romanToInt(string s) {map<char,int>m;m['I'] = 1;m['V'] = 5;m['X'] = 10;m['L'] = 50;m['C'] = 100;m['D'] = 500;m['M'] = 1000;int preNum = 0;int res = 0;for(int i = s.length() - 1;i >= 0;i--){int curNum = m[s[i]];if(curNum < preNum)res -= curNum;elseres += curNum;preNum = curNum;}return res;}
};