码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode #13 Roman to Integer (E)

时间:2015-10-09 22:56:07      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

[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;
        }        
    }
}

 

LeetCode #13 Roman to Integer (E)

标签:

原文地址:http://www.cnblogs.com/zhangqieyi/p/4865384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!