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.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"
class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        StringBuilder result = new StringBuilder();
        String sign = (numerator < 0 == denominator < 0 || numerator == 0) ? "" : "-";
        long num = Math.abs((long) numerator);
        long den = Math.abs((long) denominator);
        result.append(sign);
        result.append(num / den);
        long rem = num % den;
        if (rem == 0)
            return result.toString();
        result.append(".");
        Map<Long, Integer> map = new HashMap(); // store numerator as repetition of same numerator will cause recurring
        while (rem != 0) {
            if (!map.containsKey(rem)) {
                map.put(rem, result.length()); // for a given numerator its (num*10)/den starts from this idx
            } else {
                int idx = map.get(rem);
                return result.substring(0, idx) + "(" + result.substring(idx) + ")";
            }
            rem *= 10;
            result.append(rem / den);
            rem = rem % den;
        }
        return result.toString();
    }
}

Last updated