|
| 1 | +// https://leetcode.com/problems/fraction-to-recurring-decimal |
| 2 | +// T: O(log(n / d)) but not sure, could use some mathematician's help |
| 3 | +// S: O(log(n / d)) |
| 4 | + |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +public class FractionToRecurringDecimal { |
| 9 | + private static final String ZERO = "0"; |
| 10 | + |
| 11 | + public String fractionToDecimal(long numerator, long denominator) { |
| 12 | + if (numerator == 0) return ZERO; |
| 13 | + |
| 14 | + StringBuilder result = new StringBuilder(); |
| 15 | + result.append(isNegative(numerator, denominator) ? "-" : ""); |
| 16 | + |
| 17 | + numerator = Math.abs(numerator); |
| 18 | + denominator = Math.abs(denominator); |
| 19 | + |
| 20 | + // integral part |
| 21 | + result.append(numerator / denominator); |
| 22 | + numerator %= denominator; |
| 23 | + if (numerator == 0) return result.toString(); |
| 24 | + |
| 25 | + // fractional part |
| 26 | + result.append("."); |
| 27 | + Map<Long, Integer> map = new HashMap<>(); |
| 28 | + map.put(numerator, result.length()); |
| 29 | + |
| 30 | + while (numerator != 0) { |
| 31 | + numerator *= 10; |
| 32 | + result.append(numerator / denominator); |
| 33 | + numerator %= denominator; |
| 34 | + if (map.containsKey(numerator)) { |
| 35 | + int index = map.get(numerator); |
| 36 | + result.insert(index, "("); |
| 37 | + result.append(")"); |
| 38 | + break; |
| 39 | + } else map.put(numerator, result.length()); |
| 40 | + } |
| 41 | + |
| 42 | + return result.toString(); |
| 43 | + } |
| 44 | + |
| 45 | + private boolean isNegative(long numerator, long denominator) { |
| 46 | + return (numerator > 0) ^ (denominator > 0); |
| 47 | + } |
| 48 | +} |
0 commit comments