13. Roman to Integer
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
这里唯一需要注意的是:
IV 4 = V-I = 5-1 = 4
IX 9 = X-I = 10-1 = 9
XL 40 = L-X = 50-10 = 40
XC 90 = C-X = 100-10 = 90
CD 400 = D-C = 500-100 = 400
CM 900 = X-I = 1000-100 = 900
这几个都有一个规律:第一个字母代表的值小于第二个字母代表的值。
题目给出的罗马数字一定是从大到小(字母代表的值)(最上面的英语)。所以可以发现:只要前面的字母的值小于下一个字母的值。那么就是特殊情况。
而且值等于后面一个字母的值减去前一个字母的值。
Code:
class Solution {
public:
int romanToInt(string s) {
const map<char,int> roman{{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
int sum=0;
auto it = s.cbegin();
while(it != s.cend()){
if( (it+1 !=s.cend()) && roman.at(*it) < roman.at(*(it+1))){
sum+=roman.at(*(it+1))-roman.at(*it);
it+=2;
}
else{
sum+=roman.at(*it);
it++;
}
}
return sum;
}
};