Description
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Analysis
题目难度为:Easy
本题难度不大,只需要按照题目要求进行编码即可,同#12是一样的。不过本题有一个技巧,当小的数字在大的数字右边的时候,说明是加法,例如:XI=5+1=6;在左边的时候是减法:IX = 5-1 = 4
Code(c++)
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 res = 0, i;
for (i = 0; i < s.size()-1; ++i) {
if (m[s[i]] < m[s[i+1]]) res -= m[s[i]];
else res += m[s[i]];
}
res += m[s[i]];
return res;
}
};