Tuesday, January 6, 2015

Integer to Roman (LeetCode Math)

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

Idea: List all the possible symbols from 1000 to 1. Then add each symbol by num/symbol times.

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

Code:
 public class Solution {  
   public String intToRoman(int num) {  
     if(num==0)  
       return "";  
     int[] nums={1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};  
     String[] symbols={"M", "CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};  
     StringBuilder builder=new StringBuilder();  
     int digit=0;  
     while(num>0)  
     {  
       int times=num/nums[digit];  
       num=num-times*nums[digit];  
       while(times>0)  
       {  
         builder.append(symbols[digit]);  
         times--;  
       }  
       digit+=1;  
     }  
     return builder.toString();  
   }  
 }  

No comments:

Post a Comment