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)".
public class Solution { public String fractionToDecimal(int numerator, int denominator) { if(numerator == 0 || denominator == 0) return "0"; String sign = ""; if(numerator > 0 && denominator < 0 || numerator < 0 && denominator > 0) sign = "-"; long num = Math.abs((long) numerator); long den = Math.abs((long) denominator); long major = num / den; long rem = num % den; if(rem == 0) return sign + major; StringBuilder sb = new StringBuilder(sign + major + "."); HashMap<Long, Integer> map = new HashMap<>(); // long : rem integer 在sb中的pos while(rem != 0){ if(map.containsKey(rem)){ //相同的余数, 循环开始 int index = map.get(rem); sb.insert(index -1 , "(").append(")"); //因为sb中已经包含的循环部分;所以直接插入() break; } else{ sb.append(rem * 10 / den); map.put((rem) % den , sb.length()); } rem =rem * 10 % den; } return sb.toString(); } }