Roman To Interger
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
罗马字符的表示有I,V,X,L,C,D,M
记住前一个数字
class Solution {
public:
int romanToInt(string s) {
map<char,int> m;
m['I']=1;
m['V']=5;
m['X']=10;
m['L']=50;
m['C']=100;
m['D']=500;
m['M']=1000;
int cur=0;
int total=0;
for(int i=0;i<s.length();i++)
{
if(cur<m[s[i]])
{
total-=cur;
cur=m[s[i]];
}
else if(cur==m[s[i]])
{
cur+=m[s[i]];
}
else if(cur>m[s[i]])
{
total+=cur;
cur=m[s[i]];
}
}
total+=cur;
return total;
}
};
直接取数字比较,是否当前数字比后一个小
比前一种方法更加简洁
class Solution {
public:
int romanToInt(string s) {
map<char,int> m;
m['I']=1;
m['V']=5;
m['X']=10;
m['L']=50;
m['C']=100;
m['D']=500;
m['M']=1000;
int cur=0;
int total=0;
for(int i=0;i<s.length();i++)
{
if(i+1<s.length() && m[s[i]]<m[s[i+1]])
total-=m[s[i]];
else
total+=m[s[i]];
}
return total;
}
};