首页 > 代码库 > Roman to Integer

Roman to Integer

题目

Given a roman numeral, convert it to an integer.

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

方法

	    public int romanToInt(String s) {
	        HashMap<String, Integer> hm = new HashMap<String, Integer>();
	        hm.put("I", 1);
	        hm.put("II", 2);
	        hm.put("III", 3);
	        hm.put("IV", 4);
	        hm.put("V", 5);
	        hm.put("VI", 6);
	        hm.put("VII", 7);
	        hm.put("VIII", 8);
	        hm.put("IX", 9);
	        hm.put("X", 10);
	        hm.put("XX", 20);
	        hm.put("XXX", 30);
	        hm.put("XL", 40);
	        hm.put("L", 50);
	        hm.put("LX", 60);
	        hm.put("LXX", 70);
	        hm.put("LXXX", 80);
	        hm.put("XC", 90);
	        hm.put("C", 100);
	        hm.put("CC", 200);
	        hm.put("CCC", 300);
	        hm.put("CD", 400);
	        hm.put("D", 500);
	        hm.put("DC", 600);
	        hm.put("DCC", 700);
	        hm.put("DCCC", 800);
	        hm.put("CM", 900);
	        hm.put("M", 1000);
	        hm.put("MM", 2000);
	        hm.put("MMM", 3000);
	        int len = s.length();
	        int num = 0;
	        String currentStr = "";
	        String preStr = "";
	        for(int i = 0; i < len; i ++){
	            char ch = s.charAt(i);
	            currentStr = preStr + ch;
	            if(hm.containsKey(currentStr)){
	                preStr = currentStr;
	            }else{
	                num = num + hm.get(preStr);
	                preStr = "" + ch;
	            }
	        }
	        num = num + hm.get(preStr);
	        return num;
	    }