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

13. Roman to Integer

时间:2016-04-01 23:25:04      阅读:148      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!