166. Fraction to Recurring Decimal - jiejackyzhang/leetcode-note GitHub Wiki

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.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".

Hint:

  1. No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
  2. Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
  3. Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.

解题思路为采用hash map记住每次的余数及其位置,如果余数出现重复,则小数点后面的pattern从最初所记的位置处开始循环。

public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if(numerator == 0) return "0";
        StringBuilder res = new StringBuilder();
        String sign = (numerator > 0 == denominator > 0) ? "" : "-";
        long num = Math.abs((long) numerator);
        long den = Math.abs((long) denominator);
        res.append(sign);
        res.append(num / den);
        long remainder = num % den;
        if(remainder == 0) {
            return res.toString();
        }
        res.append(".");
        Map<Long, Integer> map = new HashMap<>();
        while(!map.containsKey(remainder)) {
            map.put(remainder, res.length());
            res.append(10 * remainder / den);
            remainder = 10 * remainder % den;
        }
        int index = map.get(remainder);
        res.insert(index, "(");
        res.append(")");
        return res.toString().replace("(0)", "");
    }
}