LeetCode 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.

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)".

题意:给出分子和分母,将小数中的循环数用括号括起来

思路:特别在不能整除时,将余数*10和小数点后的位置(从1开始)映射起来,在出现余数*10这个数时,说明有循环点。

代码如下:

class Solution
{
    public String fractionToDecimal(int numerator, int denominator)
    {
        StringBuilder ans = new StringBuilder();
        long num = numerator, deno = denominator;
        long remainder;

        if ((num < 0 && deno > 0) || (num > 0 && deno < 0)) ans.append('-');
        if (num < 0) num = -num;
        if (deno < 0) deno = -deno;

        do
        {
            remainder = num / deno;
            ans = ans.append(Long.toString(remainder));
            num %= deno;
        } while (num != 0 && num > deno);

        if (num != 0)
        {
            ans.append(".");

            Map<Long, Long> hm = new HashMap<Long, Long>();
            long cnt = 0;

            while (num != 0)
            {
                num *= 10;
                remainder = num / deno;
                if (hm.containsKey(num)) break;
                hm.put(num, ++cnt);
                num %= deno;
                ans.append(Long.toString(remainder));
            }

            if (num != 0)
            {
                System.out.println(ans.toString());
                int index = ans.toString().indexOf('.');
                ans.insert((int)(index + hm.get(num)), '(');
                ans.append(')');
            }
        }

        return ans.toString();
    }
}


你可能感兴趣的:(LeetCode Fraction to Recurring Decimal)