description:
把罗马数字转换成阿拉伯数字
Note:
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
my answer:
基本思路就是一个数字一个数字往后看,如果这个数字比前面的数字小或者相等的话就证明是正常的数字就直接往上加,反之就证明是那种4或者9,就先把现在这个数字加上之后再减两次前面那个数,因为本来是V-I,但是现在是I+V(-2*I = IV)
大佬的answer:
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++){
if(i == 0 || m[s[i]] <= m[s[i - 1]]) res += m[s[i]];
# 这个等号很重要,刚开始忘了
else {
res += m[s[i]] - 2 * m[s[i - 1]];
}
}
return res;
}
};