leetcode-13. Roman to Integer
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) {
int res = 0;
unordered_map<char, int> m = {{'I', 1},{'V', 5},{'X', 10},{'L', 50},{'C', 100},{'D', 500}, {'M', 1000}};
for(int i = 0; i < s.size(); ++i){
int val = m[s[i]];
if(i == s.size()-1 || m[s[i+1]] <= m[s[i]] )
res += val;
else
res -= val;
}
return res;
}
};