LeetCode题解-13-Roman to Integer

解题思路

题意是说罗马数字转成普通数字。

这个题目和12题是类似的,首先要理解罗马数字的表示法,它是按大小结合顺序来的,前面几个字母组合起来如果能够解释成较大的数字,那就使用这个表示,而不是按举个字母来的。

所以罗马数字转成数字,例如当前位置i的字符是c(i),对应的值是100,如果后面位置i+1的字符c(i+1),对应的值是1000,那么就应该理解成CM,对应的值是1000进去100,得到900。

结论就是在实现上,就可以这么判断,如果当前位置比后面位置的值小,那么就减去一个值,否则加上一个值。例如CM,在处理C的时候得到-100,在处理M的时候就加上1000,得到900。

参考源码

public class Solution {
    private static Map<Character, Integer> romans = new HashMap<Character, Integer>();

    static {
        romans.put('I', 1);
        romans.put('V', 5);
        romans.put('X', 10);
        romans.put('L', 50);
        romans.put('C', 100);
        romans.put('D', 500);
        romans.put('M', 1000);
    }

    public int romanToInt(String s) {
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            int n = romans.get(s.charAt(i));
            if (i < s.length() - 1 && n < romans.get(s.charAt(i + 1))) {
                sum -= n;
            } else {
                sum += n;
            }
        }
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/mccxj/article/details/60351411