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

Leetcode-Roman to Integer

时间:2014-11-29 11:36:32      阅读:148      评论:0      收藏:0      [点我收藏+]

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

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

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

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

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