Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
我是用枚举来做的,其实很容易出错,代码如下:
class Solution {
public:
int romanToInt(string s) {
// char* c[4][10]={
// {"I","II","III","IV","V","VI","VII","VIII","IX"},
// {"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
// {"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
// {"M","MM","MMM"}
// }
int sum=0;
for(auto p= s.begin();p!=s.end();p++)
{
// cout<<sum;
if(*p=='M')
{ sum+=1000;
}
else if(*p=='C' && *(p+1)=='M')
{ sum+=900; p++;}
else if(*p=='D')
{sum+=500;}
else if(*p=='C'&&*(p+1)=='D')
{sum+=400;p++;}
else if(*p=='C')
{ sum+=100;}
else if(*p=='X' &&*(p+1)=='C')
{sum+=90;p++;}
else if(*p=='L')
{sum+=50;}
else if(*p=='X' &&*(p+1)=='L')
{sum+=40;p++;}
else if(*p=='X')
{sum+=10;}
else if(*p=='I' && *(p+1)=='X')
{sum+=9;p++;}
else if(*p=='V')
{sum+=5;}
else if(*p=='I' && *(p+1)=='V')
{sum+=4;p++;}
else if(*p=='I')
{sum+=1;}
}
return sum;
}
};
网上有用map来做的,比我的做法简单。自己拿来学习学习。
代码如下:
class Solution {
public:
int romanToInt(string s) {
if(s.size()==0) return 0;
map<char,int> T{
{'I',1},
{'V',5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000}
};
int sum=T[s.back()];
for(int i= s.size()-2;i>=0;--i)
{
if(T[s[i]]<T[s[i+1]])
{
sum-=T[s[i]];
}
else
{
sum+=T[s[i]];
}
}
return sum;
}
};