2015年9月17日星期四

Leetcode 13 Roman to Integer

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

Solution 1: iterate from left to right, just keep adding related number. If see left<right, we know we must see IV, IX, XL, XC, CD, CM, then minus 2x previous number.
 public class Solution {  
   public int romanToInt(String s) {  
     int[] nums={1,5,10,50,100,500,1000};  
     char[] roman={'I','V','X','L','C','D','M'};  
     Map<Character,Integer> map=new HashMap<>();  
     for (int i=0; i<nums.length; i++) map.put(roman[i],nums[i]);  
     int n=s.length();  
     int res=0;  
     for (int i=0; i<n; i++) {  
       res+=map.get(s.charAt(i));  
       if (i>0 && map.get(s.charAt(i-1))<map.get(s.charAt(i)))   
         res-=2*map.get(s.charAt(i-1));  
     }  
     return res;  
   }  
 }  

没有评论:

发表评论