首页 > 其他 > 详细

Roman to Integer

时间:2016-01-07 13:28:50      阅读:242      评论:0      收藏:0      [点我收藏+]

 

Given a roman numeral, convert it to an integer.

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

 

public class Solution {
    public int romanToInt(String s) 
    {
        if(s == null||s.length()==0) return 0;
        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);

        int length = s.length();
        int result = map.get(s.charAt(length - 1));
        for (int i = length - 2; i >= 0; i--) {
            if (map.get(s.charAt(i + 1)) <= map.get(s.charAt(i))) {
                result += map.get(s.charAt(i));  //VI
            } else {
                result -= map.get(s.charAt(i));  //IV
            }
        }
        return result;
        
    }
}

 

Roman to Integer

原文:http://www.cnblogs.com/hygeia/p/5109391.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!