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.

做这道题目必须知道一个原则,罗马数字中如果左边的数字小于右边的数字,则要右边的数字减去左边的数字,时间复杂度为 O(n),空间复杂度为 O(1)。

代码

class Solution {
    public int romanToInt(String s) {
        if(s == null || s.length() == 0) return 0;
        int res = toNumber(s.charAt(0));
        for(int i = 1; i < s.length(); i++) {
            int valRight = toNumber(s.charAt(i));
            int valLeft = toNumber(s.charAt(i - 1));
            if(valRight > valLeft) {
                // 注意这里是减两倍的
                // 可以这么理解,减第一个是做正常的减操作,减第二个是把之前多加的给减掉
                res += valRight - 2 * valLeft;
            } else {
                res += valRight;
            }
        }
        return res;
    }
    
    public int toNumber(char c) {
        int res = 0;
        switch(c) {
            case 'I' : return 1;
            case 'V' : return 5;
            case 'X' : return 10;
            case 'L' : return 50;
            case 'C' : return 100;
            case 'D' : return 500;
            case 'M' : return 1000;
        }
        return res;
    }
}

你可能感兴趣的:(13. Roman to Integer)