What about this 12 lines 40ms Java solution?


  • 0
    H

    3 steps:

    1. treat edge cases
    2. treat sign
    3. division: left bit shift operation for divisor.
    public int divide(int dividend, int divisor) {
        // edge case
        if (divisor == 0) { return Integer.MAX_VALUE; } // 0 can not be the divisor
        if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } // int can not be 2147483648
        if (dividend == 0) { return 0; } // 0 divide any number is 0
        // get sign
        int sign = (Integer.signum(dividend)== Integer.signum(divisor))? 1:-1;
        // division
        int result = 0;
        long dividendL = Math.abs((long)dividend), divisorL = Math.abs((long)divisor);
        while (dividendL >= divisorL) {
            int shift = 1;
            while (dividendL >= (divisorL << shift)) { shift++; }
            result += 1 << (shift-1);
            dividendL -= (divisorL << shift-1);
        }
        return (sign == 1)? result : -result;
    }

Log in to reply
 

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