美文网首页
166. Fraction to Recurring Decim

166. Fraction to Recurring Decim

作者: 7ccc099f4608 | 来源:发表于2020-03-18 22:37 被阅读0次

https://leetcode-cn.com/problems/fraction-to-recurring-decimal/

image.png

(图片来源https://leetcode-cn.com/problems/fraction-to-recurring-decimal/

日期 是否一次通过 comment
2020-03-18 0
2020-03-18 0

public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
            return "0";
        }
        StringBuilder res = new StringBuilder();

        /** 异或判断符号,只要分子分母不同则为负 */
        res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
        long num = Math.abs((long) numerator);
        long den = Math.abs((long) denominator);  // 不转为long,则可能溢出

        /** 整数部分 */
        res.append(num / den);
        num %= den;
        if (num == 0) {
            return res.toString();
        }

        /** 小数部分 */
        res.append(".");
        HashMap<Long, Integer> map = new HashMap<>();  // 存放数字出现的位置
        map.put(num, res.length());
        while (num != 0) {
            num *= 10;
            res.append(num / den);
            num %= den;
            if (map.containsKey(num)) {
                int index = map.get(num);
                res.insert(index, "(");
                res.append(")");
                break;
            } else {
                map.put(num, res.length());
            }
        }

        return res.toString();
    }

相关文章

网友评论

      本文标题:166. Fraction to Recurring Decim

      本文链接:https://www.haomeiwen.com/subject/zkehyhtx.html