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

Roman to Integer

时间:2015-06-23 23:07:36      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

1. Question

罗马数转为整型,输入确保在1-3999之内。相似的题目是Integer to Roman

Given a roman numeral, convert it to an integer.

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

2. Solution

 将I:1, V:5, X:10, L:50, C:100, D:500, M:1000存储起来,依次按相加和相减规则计算即可

技术分享
public class Solution {
    
    public int romanToInt(String s){
        HashMap<Character,Integer> romanBase = new HashMap<Character,Integer>();
        romanBase.put(‘I‘,1);
        romanBase.put(‘V‘,5);
        romanBase.put(‘X‘, 10);
        romanBase.put(‘L‘, 50);
        romanBase.put(‘C‘,100);
        romanBase.put(‘D‘, 500);
        romanBase.put(‘M‘, 1000);
        
        int res = 0;
        int i;
        for( i=0; i<s.length()-1; i++ ){
            char c = s.charAt(i);
            int now = romanBase.get(c);
            int next = romanBase.get( s.charAt(i+1) );
            if( now < next ){
                res += ( next - now );
                ++i;
            }
            else
                res += now;
        }
        
        if( i==s.length()-1 )
            res += romanBase.get(s.charAt(i));
        
        return res;
    }
        
}
View Code

 

Roman to Integer

标签:

原文地址:http://www.cnblogs.com/hf-cherish/p/4596476.html

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