罗马数字转成实数。
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
。
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II
in Roman numeral, just two one's added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven is written as XXVII
, which is XX
+ V
+ II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
C++版本,一开始我的答案如下,比较复杂。
class Solution {
public:
int romanToInt(string s) {
int a=0;//出错的地方
int len = s.length();
for(int i=0;i<len;i++){
if(s[i]=='I'){
if(i<len-1){
if(s[i+1]=='V'||s[i+1]=='X'){
a-=1;
}else{
a+=1;
}
}else{
a+=1;
}
}
else if(s[i]=='X'){
if(i<len-1){
if(s[i+1]=='L'||s[i+1]=='C'){
a-=10;
}else{
a+=10;
}
}else{
a+=10;
}
}
else if(s[i]=='C'){
if(i<len-1){
if(s[i+1]=='D'||s[i+1]=='M'){
a-=100;
}else{
a+=100;
}
}else{
a+=100;
}
}
else if(s[i]=='V'){
a += 5;
}
else if(s[i]=='L'){
a += 50;
}
else if(s[i]=='D'){
a += 500;
}
else if(s[i]=='M'){
a += 1000;
}
}
return a;
}
};
LeetCode提示的错误:
在本地编译器输入III,输出是3。
(后来发现是复制过来的时候少了把int a=0……)。
C++换了种写法,使用unordered_map。在那个博客看的,不需要检查输入是否正确,罗马数字本身有以下规定:
1、基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。
2、不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。
3、V 和X 左边的小数字只能用Ⅰ。
4、L 和C 左边的小数字只能用X。
5、D 和M 左边的小数字只能用C。
(也就是不可能出现...VX...之类的)
所以只需要考虑两种情况:
第一,如果当前数字是最后一个数字,或者之后的数字比它小的话,则加上当前数字。
第二,其他情况则减去这个数字。
class Solution {
public:
int romanToInt(string s) {
if (s.size() == 0) return 0;//没有
unordered_map<char, int> map{{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}};
int pre, cur;//记录前一个后一个
int res = 0;
if (s.size() == 1) return map[s[0]];//only one
pre = map[s[0]];
for(size_t i=1; i<s.size(); i++) {
cur = map[s[i]];
if (pre < cur) {
res -= pre;
}else {
res += pre;
}
pre = cur;
}
res += pre;
return res;
}
};