Skip to content

Latest commit

 

History

History
46 lines (46 loc) · 1.65 KB

166.md

File metadata and controls

46 lines (46 loc) · 1.65 KB

#166. Fraction to Recurring Decimal 题目链接

public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0)
            return "0";
        StringBuilder sb = new StringBuilder();
        if ((numerator > 0) ^ (denominator > 0)) {
            sb.append('-');
        }
        // 考虑边界值,因为int型负数比正数多一,所以转换为long
        long num = Math.abs((long)numerator);
        long den = Math.abs((long)denominator);
        if (num < den) {
            sb.append(0);
        } else {
            sb.append(num/den);
        }
        long rest = num % den;
        if (rest == 0) {
            return sb.toString();
        }
        sb.append('.');
        Map<Long, Integer> numMap = new HashMap<>();
        int repeatFlag = 0;
        StringBuilder smallSb = new StringBuilder();
        numMap.put(rest, repeatFlag++);
        // 求小数部分,把重复余数的位置记录下来,当遇到重复余数是,说明有无限循环部分
        while (rest != 0) {
            rest *= 10;
            smallSb.append(rest / den);
            rest = rest % den;
            if (numMap.containsKey(rest)) {
                int repeatStart = numMap.get(rest);
                String snum = smallSb.toString();
                sb.append(snum.substring(0, repeatStart));
                sb.append('(').append(snum.substring(repeatStart)).append(')');
                return sb.toString();
            }
            numMap.put(rest, repeatFlag++);
        }
        return sb.append(smallSb).toString();
    }
}