← All problems

166. Fraction to Recurring Decimal

MediumOpen on LeetCodeProblem statement

Problem Statement

166. Fraction to Recurring Decimal

Medium


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.

If multiple answers are possible, return any of them.

It is guaranteed that the length of the answer string is less than 104 for all the given inputs.

 

Example 1:

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

Example 2:

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

Example 3:

Input: numerator = 4, denominator = 333
Output: "0.(012)"

 

Constraints:

Java

Source file
class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        StringBuilder quotient = new StringBuilder();
        long dividend = numerator, divisor = denominator;
        if (dividend < 0 || divisor < 0) {
            if (dividend * divisor < 0)
                quotient.append("-");
            dividend = Math.abs(dividend);
            divisor = Math.abs(divisor);
        }
        Map<Long, Integer> repeatingDividend = new HashMap<>(); // sequence -> decimal-th place
        quotient.append(dividend / divisor);
        dividend = (dividend % divisor) * 10;
        if (dividend == 0)
            return quotient.toString();
        quotient.append(".");
        while (dividend > 0) {
            quotient.append(dividend / divisor);
            dividend = (dividend % divisor) * 10;
            if (repeatingDividend.containsKey(dividend)) {
                return quotient.substring(0, repeatingDividend.get(dividend)) + "(" +
                        quotient.substring(repeatingDividend.get(dividend), quotient.length()) + ")";
            }
            repeatingDividend.put(dividend, quotient.length());
        }
        return quotient.toString();
    }
}