美文网首页程序员
166. Fraction to Recurring Decim

166. Fraction to Recurring Decim

作者: 衣介书生 | 来源:发表于2018-04-10 08:32 被阅读5次

题目分析

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

这道题目首先需要判断一些边界条件,然后判断正负,之后计算整数部分,接着计算小数部分并判断是否存在循环。

代码

class Solution {
    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);
        // 整数部分
        res.append(num / den);
        num %= den;
        // 没有小数部分
        if(num == 0) {
            return res.toString();
        }
        res.append(".");
        HashMap<Long, Integer> hm = new HashMap<>();
        hm.put(num, res.length());
        while(num != 0) {
            num *= 10;
            res.append(num / den);
            num %= den;
            if(hm.containsKey(num)) {
                int index = hm.get(num);
                res.insert(index, "(");
                res.append(")");
                break;
            } else {
                hm.put(num, res.length());
            }
        }
        return res.toString();
    }
}

相关文章

网友评论

    本文标题:166. Fraction to Recurring Decim

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