Monday, January 23, 2017

Leetcode/各大家 -- 13. Roman to Integer (Math)

13. Roman to Integer (Math, str)
easy
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

思路: 倒着走array, 如果 cur >= post (eg: XI), res += cur val,
                                   else  cur < post (eg: IX) res -= cur val


public class Solution {
    public int romanToInt(String s) {
        int res = 0;
        int len = s.length();
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        map.put('I',1);
        map.put('V',5);
        map.put('X',10);
        map.put('L',50);
        map.put('C',100);
        map.put('D',500);
        map.put('M',1000);
        res = map.get(s.charAt(len - 1));
        for(int i = len - 2; i >= 0; i--){//eg: XI = 11, IX = 9
            int cur = map.get(s.charAt(i));
            int post = map.get(s.charAt(i + 1));
            if(cur >= post){
                res += cur;
            }else{
                res -= cur;
            }
        }
        return res;
    }
}

No comments:

Post a Comment