Roman to Integer

罗马计数:

I - 1

V - 5

X - 10

L - 50

C - 100

D - 500

M - 1000

If a lower value symbol is before a higher value one, it is subtracted. Otherwise it is added.So 'IV' is '4' and 'VI' is '6'.(数字小的符号在数字大的符号之前,则为减法;否则为加法)

以上参考维基百科:http://simple.wikipedia.org/wiki/Roman_numeral。

具体编码则跟据以上的策略,着重分析相邻两个符号所代表的数字的大小关系以确定 加或者减。

public class Solution {
    
    private final Map<Character,Integer> map ;
	
	public Solution(){
		map = new HashMap<>();
		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);
	}
    public int romanToInt(String s) {
        int pre = 0;
        int cur = 1;
        int count = 0;
        for(pre=0,cur=1;cur<s.length();++pre,++cur){
        	int preNum =  map.get(s.charAt(pre));
        	int curNum =  map.get(s.charAt(cur));
        	if(preNum< curNum){
        		count -= preNum;
        	}else{
        		count += preNum;
        	}
        }
        
        count += map.get(s.charAt(pre));
        
        return count;
    }
}





转载于:https://my.oschina.net/u/1011659/blog/298367

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值