标签:leetcode
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
G)340R%X.png)
<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>标签:leetcode
原文地址:http://blog.csdn.net/yujin753/article/details/42746193