2015年9月17日星期四

Leetcode 12 Integer to Roman

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

Solution 1:  Does not necessarily need HashMap, just keep the two array with same index 
 public class Solution {  
   public String intToRoman(int num) {  
     int[] nums={1,4,5,9,10,40,50,90,100,400,500,900,1000};  
     String[] roman={"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};  
     StringBuilder res=new StringBuilder();  
     for (int i=12; i>=0; i--) {  
       while (num>=nums[i]) {  
         res.append(roman[i]);  
         num-=nums[i];  
       }  
     }  
     return res.toString();  
   }  
 }  

没有评论:

发表评论