首页 > 其他 > 详细

13. Roman to Integer

时间:2016-04-01 23:23:59      阅读:288      评论:0      收藏:0      [点我收藏+]

根据罗马数字的写法,连续出现2个或3个相同字母的情况一定是其左边有一个大数或者相等的数。即是 III 或者 VII
不存在 IIV这种写法,即不允许有连续减去两个小数的写法。

 

public class Solution {
    public int romanToInt(String s) {
        if(s.length()<1)
            return 0;
            
        int size=s.length();
        int res=0;
        
        
        Map<Character,Integer> mp=new HashMap<Character,Integer>();
        // 哈希表的正确用法
        
        mp.put(‘I‘,1);
        mp.put(‘V‘,5);
        mp.put(‘X‘,10);
        mp.put(‘L‘,50);
        mp.put(‘C‘,100);
        mp.put(‘D‘,500);
        mp.put(‘M‘,1000);
        
        //根据罗马数字的写法,连续出现2个或3个相同字母的情况一定是其左边有一个大数或者相等的数。即是 III 或者 VII
        //不存在  IIV这种写法,即不允许有连续减去两个小数的写法。
        //
        
        res=mp.get(s.charAt(size-1));
        
        for(int i=size-2;i>=0;i--)
        {
            int t=mp.get(s.charAt(i));
            int t_r=mp.get(s.charAt(i+1));
            if(t>=t_r)
                res+=t;
            else
                res-=t;
        }
        return res;
    }
}

 

13. Roman to Integer

原文:http://www.cnblogs.com/aguai1992/p/5346563.html

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