写法1
class Solution {
public:
int romanToInt(string s) {
int n=s.size(),ans=0;
unordered_map<char,int> words;
words['I']=1,words['V']=5;
words['X']=10,words['L']=50;
words['C']=100,words['D']=500;
words['M']=1000;
for(int i=0;i<n;i++)
{
if(i!=n-1&&words[s[i+1]]>words[s[i]])
{
ans+=words[s[i+1]]-words[s[i]];
i++;
}
else
ans+=words[s[i]];
}
return ans;
}
};
写法二
class Solution {
public:
int romanToInt(string s) {
s+="I";//便于for循环不用判断溢出
int n=s.size(),ans=0;
unordered_map<char,int> words;
words['I']=1,words['V']=5;
words['X']=10,words['L']=50;
words['C']=100,words['D']=500;
words['M']=1000;
for(int i=0;i<n-1;i++)
{
if(words[s[i]]>=words[s[i+1]])//i+1不会溢出
ans+=words[s[i]];
else
ans-=words[s[i]];
}
return ans;
}
};
交封不杀