Given a roman numeral, convert it to an integer.
input is guaranteed to be within the range from 1 to 3999.
题目的意思是将给定的罗马数字转换为一个整数
什么是罗马数字:
I, II, III, IV, V, VI, VII, VIII, IX, X.
上面的罗马数字表示为 1 2 3 4 5 6 7 8 9 10
在罗马数字中,各个字符对应的数字大小如上,级别最高的字符为M 其次为D 最小的为I
规则:
从右往左,遇到比上一个字符级别低的或者相同的就 加上该字符对应的数字值 表示 和累加 如VII 为 1+ 1+ 5 =7
遇到一个比上一个字符级别高就减去该字符对应的数字值,如 IV 为 5 -1=4
代码如下:
<span style="font-size:18px;">class Solution {
public:
/*
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
*/
//需要注意 罗马数字中存在减法,从后往前遍历
int romanToInt(string s) {
int result=0;
//要记录上一次出现的是哪个单位,用数字记录上一次出现的是哪个单位,分别为 1 2 3 4 5 6 7 表示 I V X L C D M
int last_show=0;//初始值为0 当上一次出现的值小于等于当前值时用加法,否则有减法
int cur_show; //当前值
for(int i=s.length()-1;i>=0;i--)
{
switch(s[i])
{
case 'I':
cur_show=1;
if(cur_show>=last_show)
result+=1;
else
result-=1;
break;
case 'V':
cur_show=2;
if(cur_show>=last_show)
result+=5;
else
result-=5;
break;
case 'X':
cur_show=3;
if(cur_show>=last_show)
result+=10;
else
result-=10;
break;
case 'L':
cur_show=4;
if(cur_show>=last_show)
result+=50;
else
result-=50;
break;
case 'C':
cur_show=5;
if(cur_show>=last_show)
result+=100;
else
result-=100;
break;
case 'D':
cur_show=6;
if(cur_show>=last_show)
result+=500;
else
result-=500;
break;
case 'M':
cur_show=7;
if(cur_show>=last_show)
result+=1000;
else
result-=1000;
break;
default:
break;
}
last_show=cur_show;
}
return result;
}
};</span>