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

Roman to Integer

时间:2014-06-17 19:27:48      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   string   

题目

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;
	    }


Roman to Integer,布布扣,bubuko.com

Roman to Integer

标签:java   leetcode   string   

原文地址:http://blog.csdn.net/u010378705/article/details/31745219

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!