coding
unsky
deepdim
thought

Roman to Integer

ID13. Roman to Integer Add to List QuestionEditorial Solution My Submissions
Total Accepted: 117446
Total Submissions: 273074
Difficulty: Easy
Contributors: Admin
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

这道题同
http://deepdim.com/2016/12/01/Integer-to-Roman/
需要特殊处理的有:

1
2
3
4
5
6
7
8
9
10
11
12
13
I: 1
IV: 4
V: 5
IX: 9
X: 10
XL: 40
L: 50
XC: 90
C: 100
CD: 400
D: 500
CM: 900
M: 1000

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int romanToInt(string s) {
string roman[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int num[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
int i=0,index=0,result=0;
string CurString;
while(i<13)
{ CurString=s.substr(index,roman[i].size());
if(CurString==roman[i])
{result=result+num[i];
index=index+roman[i].size();
cout<<num[i]<<endl;
}
else if((CurString!=roman[i])||s.substr(index+roman[i].size(),roman[i].size())!=roman[i])
i++;
}
return result;
}
};

其中较为关键的是判断什么时候进行i++
if((CurString!=roman[i])||s.substr(index+roman[i].size(),roman[i].size())!=roman[i])
即只有在当前不匹配或者下个不匹配的时候才进行i++从而实现了最大三个字母的重复。。

坚持原创技术分享,您的支持将鼓励我继续创作!