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

[LintCode] Roman to Integer

时间:2017-06-23 10:13:54      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:blog   following   within   org   with   null   mapped   val   ref   

Given a roman numeral, convert it to an integer.

The answer is guaranteed to be within the range from 1 to 3999.

Example

IV -> 4

XII -> 12

XXI -> 21

XCIX -> 99

 

Observation:  if s.charAt(i) > s.charAt(i - 1), it means we need to subtract the mapped value of s.charAt(i - 1) from the mapped value of s.charAt(i).

Based on this observation, the following algorithm is developed.

1. init result to m.get(s.charAt(length - 1)), the mapped value of the last character.

2. starting from the 2nd last character, iterate through the string from right to left; if the current character‘s mapped value is smaller than

its right neighbor‘s, subtract this mapped value from the result; if not, add this mapped value to the result.

 1 public class Solution {
 2      public int romanToInt(String s) {
 3         if (s == null || s.length()==0) {
 4                 return 0;
 5         }
 6         Map<Character, Integer> m = new HashMap<Character, Integer>();
 7         m.put(‘I‘, 1);
 8         m.put(‘V‘, 5);
 9         m.put(‘X‘, 10);
10         m.put(‘L‘, 50);
11         m.put(‘C‘, 100);
12         m.put(‘D‘, 500);
13         m.put(‘M‘, 1000);
14 
15         int length = s.length();
16         int result = m.get(s.charAt(length - 1));
17         for (int i = length - 2; i >= 0; i--) {
18             if (m.get(s.charAt(i + 1)) <= m.get(s.charAt(i))) {
19                 result += m.get(s.charAt(i));
20             } else {
21                 result -= m.get(s.charAt(i));
22             }
23         }
24         return result;
25     }
26 }

 

Related Problems

Integer to Roman

[LintCode] Roman to Integer

标签:blog   following   within   org   with   null   mapped   val   ref   

原文地址:http://www.cnblogs.com/lz87/p/7067944.html

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