1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public String fractionToDecimal(int numerator, int denominator) { long a = numerator, b = denominator; if (a % b == 0) return String.valueOf(a / b); StringBuilder builder = new StringBuilder(); if (a * b < 0) { builder.append('-'); a = Math.abs(a); b = Math.abs(b); } builder.append(a / b).append("."); a %= b; Map<Long, Integer> map = new HashMap<>(); while (a != 0) { map.put(a, builder.length()); a *= 10; builder.append(a / b); a %= b; if (map.containsKey(a)) { int length = map.get(a); return String.format("%s(%s)" , builder.substring(0, length), builder.substring(length)); } } return builder.toString(); } }
|