Java ac solution: bit operation


  • 0
    H
    public int divide(int dividend, int divisor) {
        if (divisor == 0) return Integer.MAX_VALUE;
        
        long l_dividend = Math.abs((long)dividend);
        long l_divisor = Math.abs((long)divisor);
        long res = 0;
        long tmp = l_divisor;
    
        while (tmp <= l_dividend) { tmp <<= 1; }
        while (tmp > l_divisor) {
            tmp >>= 1;
            res <<= 1;
            if (l_dividend < tmp) continue;
            l_dividend -= tmp;
            res |= 1;
        }
        res = (dividend ^ divisor) >= 0 ? res : (~res+1); //positive or negative
        if (res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        if (res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        return (int)res;
    }

Log in to reply
 

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