LeetCode #13 Roman to Integer (E)

[Problem]

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

 

[Analysis]

建立一个字符到数字的map之后只需要抓住两个条件:1. 输入都是有效罗马数字; 2. 当小数字在大数字左边时需要用到减法。

 

[Solution]

public class Solution {
    public int romanToInt(String s) {
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            int curVal = romanToDigit(s.charAt(i));
            if (i + 1 < s.length()) {
                int nextVal = romanToDigit(s.charAt(i + 1));
                if (nextVal > curVal) {
                    result += nextVal - curVal;
                    i++;
                } else {
                    result += curVal;
                }
            } else {
                result += curVal;
            }            
        }
        return result;
    }
    
    public int romanToDigit(char c) {
        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;  
            default: return 0;
        }        
    }
}

 

posted on 2015-10-09 22:28  张惬意  阅读(107)  评论(0编辑  收藏  举报