Friday, December 26, 2014

Fraction to Recurring Decimal (LeetCode HashMap)

Question: Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".

Idea: As in primary school, keep multiplying the remainder by 10 and dividing by the denominator until the remainder becomes 0 or the same remainder appears before (this is the start point of the repeating part). So we need to use a HashMap <remainder, last time shown in the result string> to store the position to insert the parentheses.

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

Code:
 public class Solution {  
   public String fractionToDecimal(int numerator, int denominator) {  
     StringBuilder builder=new StringBuilder();  
     long num=numerator;  
     long deno=denominator;  
     if((num>0&&deno<0)||(num<0&&deno>0))  
     {  
       builder.append("-");  
     }  
     num=Math.abs(num);  
     deno=Math.abs(deno);  
     builder.append(num/deno);  
     long remainder=num%deno;  
     if(remainder!=0)  
     {  
       builder.append(".");  
     }  
     HashMap<Long,Integer> rToPos=new HashMap<Long,Integer>();  
     while(!rToPos.containsKey(remainder)&&remainder!=0)  
     {  
       rToPos.put(remainder,builder.length());  
       remainder=remainder*10;  
       builder.append(remainder/deno);  
       remainder=remainder%deno;  
     }  
     if(rToPos.containsKey(remainder))  
     {  
       builder.insert(rToPos.get(remainder),"(");  
       builder.append(")");  
     }  
     return builder.toString();  
   }  
 }  

No comments:

Post a Comment