标签:
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,
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
标签:
原文地址:http://www.cnblogs.com/birdhack/p/4179114.html