Simple Java solution with explanation for all key points


  • 2
    L
    public String fractionToDecimal(int numerator, int denominator) {
            //1. Handle 3 special cases and return directly.
            //1) Zero divisor
            if (denominator == 0) return "Error: 0 cannot be a denominator!";
            //2) Zero dividend
            if (numerator == 0) return "0";
            //3) Exact division
            if (numerator % denominator == 0) return String.valueOf((long)numerator / (long)denominator);
            //NOTE: Convert to long before dividing to avoid overflow.
    
            //2. Handle indivisible case
            StringBuilder sb = new StringBuilder();
    
            //1) Add "-" sign for negative numbers
            long num = Math.abs((long)numerator);
            long den = Math.abs((long)denominator);
            //NOTE: MUST convert int to long before abs() since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE.
    
            if ( (long)numerator * (long)denominator < 0) sb.append("-");
            //NOTE:
            // -- This is mandatory when num < den.
            // -- Convert to long before * to avoid overflow.
    
            //2) Add integral part and "."
            sb.append(num / den).append(".");
            //NOTE: Use ABS() value to avoid double "-" sign when abs(num)>abs(den).
    
            //3) Handle fraction part
            long remainder = num % den;
            Map<Long/*current reminder*/, Integer/* current stringBuilder.length()*/> map =
                    new HashMap<Long, Integer>();
            //Assumption: a repeat remainder indicate a recursion of fraction.
            while (!map.containsKey(remainder)) {
                map.put(remainder, sb.length());
                sb.append(remainder * 10 / den);    //current fraction digit
                remainder = remainder * 10 % den;   //next reminder
            }
    
            sb.insert(map.get(remainder), "("); //Insert "(" before the start of recursion.
            sb.append(")"); //Append ")" at the end.
            return sb.toString().replace("(0)", "");    //Remove "(0)" when no recursion.
        }
    

Log in to reply
 

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