Leetcode-Roman to Integer

LiBlog發表於2014-11-29

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 }

 Solution 2:

Whenever the value of char i is smaller than the value of char i+1, then the value of char i should be reduced from the sum.

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

 

相關文章