Roman to Integer

罗马计数: java

I - 1 编码

V - 5 spa

X - 10 code

L - 50 orm

C - 100 ip

D - 500 get

M - 1000 it

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'.(数字小的符号在数字大的符号以前,则为减法;不然为加法) io

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

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

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;
    }
}
相关文章
相关标签/搜索