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

LeetCode Roman to Integer

时间:2014-11-27 01:28:59      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

Given a roman numeral, convert it to an integer.

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

 1 public class Solution {
 2     public int romanToInt(String s) {
 3         int res=0;
 4         HashMap<String, Integer> map = new HashMap<String, Integer>();
 5         map.put("M", 1000);map.put("CM", 900);map.put("D", 500);map.put("CD", 400);
 6         map.put("C", 100);map.put("XC", 90);
 7         map.put("L", 50);map.put("XL", 40);map.put("X", 10);map.put("IX", 9);map.put("V", 5);
 8         map.put("IV", 4);map.put("I",1);
 9         if (s.equals("")) return 0;
10         if (s.length()==1) return map.get(s);
11         String ss;
12         for (int i = 0; i < s.length(); i++) {
13             if (i<s.length() - 1) {
14                 ss = s.substring(i, i + 2);
15             }else {
16                 ss = s.substring(i, i + 1);
17             }
18 
19             if (map.containsKey(ss)) {
20                 res = res + map.get(ss);
21                 ++i;
22             } else {
23                 ss = s.substring(i, i + 1);
24                 res = res + map.get(ss);
25             }
26         }
27         return res;
28     }
29 }

 

LeetCode Roman to Integer

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/birdhack/p/4125408.html

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