Wednesday, January 7, 2015

Roman to Integer (LeetCode Math)

Question: Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

Idea: Let us just have a look serval numbers, then the algorithm will be very obvious.
1: I
2: II
3: III
4: IV
5: V
6: VI
7: VII
8: VIII
9: IX
10: X
We can observe that to represent any number
1) a smaller symbol on the left of a bigger symbol == need to minus the value of this smaller symbol.
2) a smaller symbol on the right of a bigger symbol == need to add the value of this smaller symbol.
3) there will no be more than one smaller symbol on the left of the bigger symbol, e.g IV, IX. There are no IIV (III), IIX (VIII).

So the algorithm is clear. Scan the string from right to left. If there is any symbol is smaller than the symbol on its right, minus its value, otherwise add its value.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public int romanToInt(String s) {  
     int[] num={1,5,10,50,100,500,1000};  
     char[] symbols={'I','V','X','L','C','D','M'};  
     HashMap<Character,Integer> map=new HashMap<Character,Integer>();  
     for(int i=0;i<num.length;i++)  
       map.put(symbols[i],num[i]);  
     int result=0;  
     for(int i=s.length()-1;i>=0;i--)  
     {  
       char c=s.charAt(i);  
       if(i==s.length()-1)  
       {  
         result+=map.get(c);  
       }  
       else  
       {  
         char last=s.charAt(i+1);  
         int val=(map.get(c)>=map.get(last))?map.get(c):-map.get(c);  
         result+=val;  
       }  
     }  
     return result;  
   }  
 }  

No comments:

Post a Comment