Fraction to Recurring Decimal

2020-07-01  本文已影响0人  瞬铭

https://leetcode.com/problems/fraction-to-recurring-decimal/
给定一个除数,一个被除数,用string表示他们的返回值,如果出现了循环,则用"()"代替

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

        //只有当一个为正,一个为负
        //true ^ false = true
        if (numerator < 0 ^ denominator < 0) {
            fraction.append("-");
        }

        //转化成long
        long dividend = Math.abs(Long.valueOf(numerator));
        long divisor = Math.abs(Long.valueOf(denominator));

        //小数点前的那一位,直接用除法可以得到
        fraction.append(String.valueOf(dividend / divisor));
        long remainder = dividend % divisor;

        //除完余数为0,直接返回,不用计算小数点后面的值
        if (remainder == 0) {
            return fraction.toString();
        }
        fraction.append(".");
        Map<Long, Integer> map = new HashMap<>();
        while (remainder != 0) {
            if (map.containsKey(remainder)) {
                fraction.insert(map.get(remainder), "(");
                fraction.append(")");
                break;
            }
            map.put(remainder, fraction.length());
            remainder *= 10;
            fraction.append(String.valueOf(remainder / divisor));
            remainder %= divisor;
        }
        return fraction.toString();
    }
上一篇下一篇

猜你喜欢

热点阅读