Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
int romanToInt(string s)
{
int roman[128];
roman['I'] = 1;
roman['V'] = 5;
roman['X'] = 10;
roman['L'] = 50;
roman['C'] = 100;
roman['D'] = 500;
roman['M'] = 1000;
int ans = 0;
int pre;
//大数后面是小数,则减;
//大数前面是小数,则加;
for(int i = s.size() - 1; i >= 0; i--)
{
if(ans == 0)
{
ans = roman[s[i]];
}
else
{
if(pre > roman[s[i]])
{
ans -= roman[s[i]];
}
else
{
ans += roman[s[i]];
}
}
pre = roman[s[i]];
}
return ans;
}
};
罗马数字简介,参考:
[LeetCode]Integer to Roman - Jet_yingjia的专栏 - 博客频道 - CSDN.NET
http://blog.csdn.net/jet_yingjia/article/details/25814977