首页 > 其他 > 详细

Leetcode-Roman to Integer

时间:2014-11-29 11:34:28      阅读:232      评论:0      收藏:0      [点我收藏+]

Given a roman numeral, convert it to an integer.

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

Solution:

 1 public class Solution {
 2     public int romanToInt(String s) {
 3         if (s.length()==0) return 0;
 4 
 5         Map<Character,Integer> map = new HashMap<Character,Integer>();
 6         map.put(‘I‘,1);
 7         map.put(‘V‘,5);
 8         map.put(‘X‘,10);
 9         map.put(‘L‘,50);
10         map.put(‘C‘,100);
11         map.put(‘D‘,500);
12         map.put(‘M‘,1000);
13         
14         int res = 0;
15         int index = 0;
16         while (index<s.length()){
17             char cur = s.charAt(index);
18             if (index+1<s.length()){
19                 char next = s.charAt(index+1);
20                 int val1 = map.get(cur);
21                 int val2 = map.get(next);
22                 if (val1<val2){
23                     res += (val2-val1);
24                     index += 2;
25                 } else {
26                     res += val1;
27                     index++;
28                 }
29             } else {
30                 int val = map.get(cur);
31                 res += val;
32                 index++;
33             }
34         }
35 
36         return res;       
37     }
38 }

 

Leetcode-Roman to Integer

原文:http://www.cnblogs.com/lishiblog/p/4130395.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!