首页 > 代码库 > LeetCode Fraction to Recurring Decimal

LeetCode 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)".

 

Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.

 1 public class Solution { 2     public String fractionToDecimal(int numerator, int denominator) { 3         if (numerator==0) { 4             return "0"; 5         } 6         String result=""; 7         if (numerator<0 ^ denominator<0) { 8             result+="-"; 9         }10         long n=numerator;11         long d=denominator;12         n=Math.abs(n);13         d=Math.abs(d);14         long r=n%d;15         result+=n/d;16         if (r==0) {17             return result;18         }else {19             result+=".";20         }21         HashMap<Long, Integer> map=new HashMap<>();22         while (r>0) {23             if (map.containsKey(r)) {24 25                 result=result.substring(0, map.get(r))+"("+result.substring(map.get(r))+")";26                 return result;27             }else {28                 map.put(r, result.length());29                 r*=10;30                 result+=r/d;31                 r=r%d;    32             }33         }34         return result;35     }36 }

 

LeetCode Fraction to Recurring Decimal