2015年10月24日星期六

Leetcode 166 Fraction to Recurring Decimal

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)".
Solution 1: Integer part is relatively easy. Fractional part: use a hash table to record to find the duplication numerator which mean fractional part will repeat, or if numerator part is zero, which means end of the fractional part.
 public class Solution {  
   public String fractionToDecimal(int numerator, int denominator) {  
     boolean pos=true;  
     if (numerator==0) return "0";  
     if (numerator<0) pos=!pos;  
     if (denominator<0) pos=!pos;  
     StringBuilder res=new StringBuilder();  
     if (!pos) res.append('-');  
     long n=Math.abs((long)numerator);  
     long d=Math.abs((long)denominator);  
     res.append(String.valueOf(n/d));  
     n%=d;  
     if (n==0) return res.toString();  
     res.append('.');  
     Map<Long,Integer> map=new HashMap<>();  
     StringBuilder sb=new StringBuilder();  
     int i=0;  
     while (n!=0) {  
       if (map.containsKey(n)) {  
         sb.insert((int)map.get(n),'(');  
         sb.append(')');  
         break;  
       }  
       else {  
         map.put(n,i++);  
         sb.append((char)(n*10/d+'0'));  
         n=n*10%d;  
       }  
     }  
     res.append(sb);  
     return res.toString();  
   }  
 }  

没有评论:

发表评论