18-line java, beat 54%


  • 0
    A
    public String fractionToDecimal(int numerator, int denominator) {
        StringBuilder sb = new StringBuilder();
        long num = (long)numerator, den = (long)denominator;
        if(num * den == 0) return "0";
        if(num * den < 0) sb.append("-");
        Map<Long, Integer> map = new HashMap<>();
        num = Math.abs(num); den = Math.abs(den);
        sb.append(num/den);
        num %= den;
        if(num == 0) return sb.toString();
        sb.append(".");
        while(num!=0 && !map.containsKey(num)){
            map.put(num, sb.length());
            sb.append(num * 10 / den);
            num = num * 10 % den;
        }
        if(num != 0) sb.insert(map.get(num), "(").append(")");
        return sb.toString();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.