Leetcode 题目解析之 Fraction to Recurring Decimal

2022-01-10 20:18:25 浏览数 (1)

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)".
代码语言:txt复制
    public String fractionToDecimal(int numerator, int denominator) {
        String sign = "";
        if (Math.signum(numerator) * Math.signum(denominator) < 0) {
            sign = "-";
        }
        long n = Math.abs(numerator);
        long d = Math.abs(denominator);
        String intPart = Math.abs(n / d)   "";
        // 如果整除,直接返回结果
        if (n % d == 0) {
            return sign   intPart;
        }
        // 计算小数部分
        n %= d;
        n *= 10;
        StringBuilder sb = new StringBuilder();
        Map<Long, Integer> mod = new HashMap<Long, Integer>();
        for (int i = 0; n != 0; i  ) {
            long q = n / d;
            Integer start = mod.get(n / 10);
            if (start != null) {
                sb.insert(start, "(");
                sb.append(")");
                break;
            }
            sb.append(Math.abs(q));
            mod.put(n / 10, i);
            n %= d;
            n *= 10;
        }
        String fractionalPart = sb.toString();
        return sign   intPart   "."   fractionalPart;
    }

0 人点赞