来源:Leetcode
原帖:http://oj.leetcode.com/problems/roman-to-integer/
题目:
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
代码:
原帖:http://oj.leetcode.com/problems/roman-to-integer/
题目:
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) {
unordered_map<char, int> roman = {{'M', 1000}, {'D', 500}, {'C', 100},
{'L', 50}, {'X', 10}, {'V', 5}, {'I', 1}};
int res = 0, N = s.size();
for (int i = 0; i < N; ++i) {
if (i < N - 1 && roman[s[i]] < roman[s[i + 1]]) {
res -= roman[s[i]];
} else {
res += roman[s[i]];
}
}
return res;
}
};
No comments:
Post a Comment