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)".
分析:https://segmentfault.com/a/1190000003794677
哈希表法
复杂度
时间 O(N) 空间 O(N)
思路
整数部分很好处理,只要注意正负号的区分就行了,但是如何处理小数部分呢。如果只是简单的除法,那我们每次把余数乘以10,再除以被除数就可以得到当前位的小数了,得到新的余数,直到余数为0。难点在于,对于无尽循环小数,我们一直这么做永远也不能让余数变为0。这里我们可以用一个哈希表记录每次的余数,如果余数出现重复的时候,说明就产生循环了。为了能找出小数中循环的部分,我们在用哈希表时,还要把每个余数对应的小数位记录下来,这样子我们一旦遇到重复,就知道是从哪里开始循环的。
注意
如果输入的被除数很大,那么余数乘以10有可能溢出,所以我们用long来保存numerator和denominator。
1 public class Solution { 2 public String fractionToDecimal(int numerator, int denominator) { 3 long num = numerator, den = denominator; 4 if (num == 0 || den == 0) return "0"; 5 boolean negative = (num > 0 && den < 0) || (num < 0 && den > 0); 6 num = Math.abs(num); 7 den = Math.abs(den); 8 String integ = (negative ? "-" : "") + String.valueOf(num / den); 9 num = num % den; 10 if (num != 0) { 11 HashMap<Long, Integer> map = new HashMap<>(); 12 int pos = 0; 13 StringBuilder frac = new StringBuilder(); 14 while (num != 0) { 15 map.put(num, pos); 16 num = num * 10; 17 frac.append(num / den); 18 num = num % den; 19 if (map.containsKey(num)) { 20 // 将非循环部分和循环部分分开 21 String pre = frac.substring(0, map.get(num)); 22 String loop = frac.substring(map.get(num)); 23 return integ + "." + pre + "(" + loop + ")"; 24 } 25 pos++; 26 } 27 return integ + "." + frac.toString(); 28 } 29 return integ; 30 } 31 }