题目:罗马数字转整数
不同的是,这次并没有将4,9等特殊数字存储进来,而是选择在后面的分支中进行处理:如果下一个字符代表的数字大于当前字符,那么就减去当前字符代表的数字(如:此次读取到了I,而下一个字符为V,也就是说这两个字符本来是连在一起的(IV:4),这是就需要减去1,而5会在下一次循环中加上去)
1class Solution
2{
3public:
4 unordered_map<char, int> symbolValues =
5 {
6 {'I', 1},
7 {'V', 5},
8 {'X', 10},
9 {'L', 50},
10 {'C', 100},
11 {'D', 500},
12 {'M', 1000},
13 };
14
15 int romanToInt(string s)
16 {
17 int res = 0;
18 int n = s.size();
19 for(int i = 0; i < n; i++)
20 {
21 int currValue = symbolValues[s[i]];
22 if (i < n - 1 && currValue < symbolValues[s[i + 1]])
23 res -= currValue;
24 else
25 res += currValue;
26 }
27 return res;
28 }
29};
来源:语雀原笔记