Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
一些背景知识:
【罗马数字】
1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
1000~3000: {"M", "MM", "MMM"}.
比如: 数字3291 对应的就是: MMMCCXCI
Roman 转 int 的程序如下:
class Solution {
public:
//example: MMMCCXCI --> 3291 , s[0]=M
int romanToInt(string s) {
int ret = 0;
for(int i=0; i< s.length(); i++)
{
if(toNumber(s[i]) < toNumber(s[i+1]))
{
ret -= toNumber(s[i]);
}
else
{
ret += toNumber(s[i]);
}
}
return ret;
}
int toNumber(char ch)
{
switch(ch)
{
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
}
return 0;
}
};