My concise 20-line Java solution with comments


  • 0

    Re: My clean Java solution Thanks for sharing. Here is my solution which comes up when I practice this problem the second time. Much similar idea but a little shorter.

        // Eg. 4 / 333
        // ret="0."    i=2  num=4 (->40)   map=[4-2]
        // ret="0.0"   i=3  num=40(->400)  map=[4-2,40-3]
        // ret="0.01"  i=4  num=400(->67)  map=[4-2,40-3,400-4]
        // ret="0.012" i=5  num=67(->4)    map=[4-2,40-3,400-4,67-5]
        // num=4 terminates
        public String fractionToDecimal(int numerator, int denominator) {
            if (numerator == 0) return "0";
            StringBuilder ret = new StringBuilder((numerator < 0) ^ (denominator < 0) ? "-" : "");
            long num = Math.abs((long) numerator);
            long denom = Math.abs((long) denominator);
            ret.append(num / denom);                    // Integral part
            num %= denom;
            ret.append(num != 0 ? "." : "");
            
            Map<Long,Integer> seen = new HashMap<>();
            for (int i = ret.length(); num != 0; i++) { // Fractional part
                Integer idx;
                if ((idx = seen.put(num, i)) != null)
                    return ret.insert(idx, "(").append(")").toString();
                num *= 10;                              // note: must put here!
                if (num >= denom) {
                    ret.append(num / denom);
                    num %= denom;
                } else
                    ret.append(0);
            }
            return ret.toString();
        }
    

Log in to reply
 

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