Total Accepted: 133406
Total Submissions: 301893
Difficulty: Easy
Contributors: Admin
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
int romanToInt(string s) {
int sum = 0;
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;
for(int i=0;i<s.length()-1;++i)
{
if(m[s[i]]>=m[s[i+1]])
sum+=m[s[i]];//右边的而且小的相加
else
sum-=m[s[i]];//左边的而且大的相减
}
return sum+m[s[s.length()-1]];//算上最后一个元素
}
};