Java solution uses bit operation 82.64%


  • 0
    D

    Image the dividend and divisor can be represented as a * 2^n + b * 2^(n-1) ..... e * 2^0.
    Then, use bitwise operation to count the result

    public int divide(int dividend, int divisor) {
        if (divisor == 0) return Integer.MAX_VALUE;
        if(divisor==-1 && dividend == Integer.MIN_VALUE) return Integer.MAX_VALUE;
        //get positive values
        long pDividend = Math.abs((long)dividend);
        long pDivisor = Math.abs((long)divisor);
        int count = 0;
        while(pDividend >= pDivisor) {
            int shift = 0;
            while (pDividend >= (pDivisor << shift)) shift++;
            count += (1 << (shift - 1));
            pDividend -= (pDivisor << (shift - 1));
        }
        if ((dividend > 0) ^ (divisor > 0)) {
            return -1 * count;
        } else {
            return count;
        }
    }

Log in to reply
 

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