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.
Example :
Given numerator = 1, denominator = 2, return "0.5"
Given numerator = 2, denominator = 1, return "2"
Given numerator = 2, denominator = 3, return "0.(6)"
Method:
When we see the same remainder twice, we know there is a repeating pattern in the decimal.
Solution:
Time: O(n) Space: O(n)
public class Solution { public String fractionToDecimal(int A, int B) { boolean negative = (A < 0) ^ (B < 0); StringBuilder sb = new StringBuilder(); long a = Math.abs((long) A); long b = Math.abs((long) B); long q = a / b; sb.append(q + ""); if (b * q == a) { if (q == 0 || !negative) { return sb.toString(); } else { sb.insert(0, "-"); return sb.toString(); } } sb.append("."); StringBuilder decimal = new StringBuilder(); Map<Long, Integer> map = new HashMap<>(); long repeating = -1; long r = a - b * q; while (r > 0) { if (map.containsKey(r)) { repeating = r; break; } else { map.put(r, decimal.length()); r = r * 10; q = r / b; decimal.append(q + ""); r = r - b * q; } } if (negative) sb.insert(0, "-"); if (repeating != -1) decimal.insert(map.get(repeating), "("); sb.append(decimal.toString()); if (repeating != -1) sb.append(")"); return sb.toString(); } }