Sunday, January 12, 2014

RomanToInteger LeetCode

唯一需要注意的是,100,10,1有可能是负的。判断一下就好。

public int romanToInt(String s) {
        int[] numbers = {1000, 500, 100, 50, 10, 5, 1};
        char[] symbols = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
        for (int i=0; i<numbers.length; i++){
            hm.put(symbols[i], numbers[i]);
        }
        //calculate the integer
        char[] charArr = s.toCharArray();
        int result = hm.get(charArr[s.length()-1]);
        for (int i=0; i<s.length()-1; i++){
            result += hm.get(charArr[i])
                    *(hm.get(charArr[i])>=hm.get(charArr[i+1]) ? 1 : -1);
        }
        return result;
    }

No comments:

Post a Comment