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)".
Hint:
- No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
- Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
- Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
本题之所以AC率如此的低是因为有很多的陷阱:int要转换成long型,并且要先转换再绝对值。思路是这样的,创建一个StringBuilder,然后判断符号,如果为负数,则把“-”输入到动态字符串里面,然后让被除数除以除数,商输入到动态字符串里面,检测余数,如果余数为0,则返回,否则,创建一个hashmap,用来存储余数,进入循环,将余数*10/除数存到动态字符串里面,看其余数,如果余数在hashmap里面出现,则说明是循环的,加入括号;否则,map里面加入余数;代码如下:
1 public class Solution { 2 public String fractionToDecimal(int numerator, int denominator) { 3 if(numerator==0) return "0"; 4 long num = Math.abs((long)numerator); 5 long den = Math.abs((long)denominator); 6 StringBuilder sb = new StringBuilder(); 7 sb.append((numerator>0)^(denominator>0)?"-":""); 8 sb.append(num/den); 9 num = num%den; 10 if(num==0) return sb.toString(); 11 sb.append("."); 12 Map<Long,Integer> map = new HashMap<Long,Integer>(); 13 map.put(num,sb.length()); 14 while(num!=0){ 15 num = num*10; 16 sb.append(num/den); 17 num = num%den; 18 if(map.containsKey(num)){ 19 int index = map.get(num); 20 sb.insert(index,"("); 21 sb.append(")"); 22 break; 23 } 24 map.put(num,sb.length()); 25 } 26 return sb.toString(); 27 } 28 }