166. 分數到小數

宇智波愛程式設計發表於2020-09-26
public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
            return "0";
        }

        StringBuilder sb = new StringBuilder();
        if (numerator < 0 ^ denominator < 0) {
            sb.append("-");
        }

        long dividend = Math.abs((long) numerator);
        long divisor  = Math.abs((long) denominator);

        sb.append(dividend / divisor);
        long remainder = dividend % divisor;

        if (remainder == 0) {
            return sb.toString();
        }

        Map<Long, Integer> map = new HashMap<>();
        sb.append('.');
        while (remainder != 0) {
            if (map.containsKey(remainder)) {
                sb.insert(map.get(remainder), "(");
                sb.append(')');
                break;
            }
            map.put(remainder, sb.length());
            remainder *= 10;
            sb.append(remainder / divisor);
            remainder = remainder % divisor;
        }

        return sb.toString();
    }

相關文章