class Solution {
public:
int romanToInt(string s) {
//此处用到了map
map<char,int> m;
//通过下表添加map对象
m['I'] = 1;
m['V'] = 5;
m['X'] = 10;
m['L'] = 50;
m['C'] = 100;
m['D'] = 500;
m['M'] = 1000;
//从尾部遍历
int result;
for(int i=s.length()-1;i>=0;i--)
{
if(i==s.length()-1)
{
result=m[s[i]];
continue;
}
if(m[s[i]] >= m[s[i+1]])
result+=m[s[i]];
else
result-=m[s[i]];
}
return result;
}
};
13.[LeetCode]Roman to Integer
最新推荐文章于 2024-08-25 17:36:33 发布