这个题首先要知道的转换的规则,百度处了两条:
有两条须注意掌握:
-
1.基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数的左边只能用一个;
-
2.不能把基本数字 V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目、只能使用一个;
基本字符 |
I
|
V
|
X
|
L
|
C
|
D
|
M
|
---|---|---|---|---|---|---|---|
相应的阿拉伯数字表示为 |
1
|
5
|
10
|
50
|
100
|
500
|
1000
|
-
相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
-
小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
-
小的数字(限于 I、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
-
正常使用时、连写的数字重复不得超过三次;
-
在一个数的上面画一条横线、表示这个数扩大 1000 倍。
OK,那经过分析就3种特殊情况。找出来就好。
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int romanToInt(string s) {
int l=s.length();
int pre=0,now=0,ans=0;
for(int i=0;i<l;i++){
if(s[i]=='I'){ now=1;
if(i+1<l&&s[i+1]=='V') { now=4; i++; }
else if(i+1<l&&s[i+1]=='X') { now=9; i++; }
}
else if(s[i]=='X') { now=10;
if(i+1<l&&s[i+1]=='L') { now=40; i++; }
else if(i+1<l&&s[i+1]=='C') { now=90; i++; }
}
else if(s[i]=='C') { now=100;
if(i+1<l&&s[i+1]=='D') { now=400; i++; }
else if(i+1<l&&s[i+1]=='M') { now=900; i++; }
}
else if(s[i]=='M') { now=1000; }
else if(s[i]=='V') { now=5; }
else if(s[i]=='L') { now=50; }
else if(s[i]=='D') { now=500; }
ans+=now;
}
return ans;
}
};
int main()
{
Solution b;
cout<<b.romanToInt("MCMLXXXIV")<<endl;
return 0;
}