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.

给出罗马数字 输出对应的阿拉伯数字。思路来自29的罗马数字

观看罗马数字构造规则(http://www.jianshu.com/p/0ecc70f62bb7)我们可以发现相邻的两个字符 如果第一个比第二个大 那么第二个字符要么和第三个字符组成(10-1,100-10等组合)要么就是末尾的字符。而第一个字符只要把他带代表的阿拉伯数字加上就可以了。第二个字符可以根据下标i判断是不是末尾字符。

class Solution {
public:
    int get(char c) {
        if (c == 'I') return 1;
        else if (c == 'V') return 5;
        else if (c == 'X') return 10;
        else if (c == 'L') return 50;
        else if (c == 'C') return 100;
        else if (c == 'D') return 500;
        else if (c == 'M') return 1000;
    }
    int romanToInt(string s) {
        if (s.size() == 1) return get(s[0]);
        int sum = 0;
        int mark = 0;
        for (int i = 0; i < s.size() - 1; ++i) {
            int x = get(s[i]);
            int y = get(s[i + 1]);
            //cout << x << " "<< y<<endl;
            if (x < y) {
                sum += y - x,++i; 
                if (i == s.size() - 2) mark = get(s[s.size() - 1]);
            }
            else {
                sum += x;
                if (i == s.size() - 2) mark = y;
            }
        }
        return sum + mark;
    }
};
原文地址:https://www.cnblogs.com/pk28/p/7197185.html