O(1) solution with bit manipulation


  • 0
    B

    if m / k > n, then result number has a k component.

    private long div(long m,long n){
            long result = 0;
            for(int i = 31;i>=0;i--){
                if((m >> i) >= n){
                    result |= (1L << i);
                    m -= (n << i);
    
                }
            }
            return result;
        }
    
        public int divide(int dividend, int divisor) {
            if(divisor == 0) return Integer.MAX_VALUE;
            if(dividend == divisor) return 1;
    
            int sign = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0) ? 1 : -1;
            long m = Math.abs((long)dividend);
            long n = Math.abs((long)divisor);
    
            long result = div(m,n);
            if(sign * result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            return (int) (sign * result);
        }
    

Log in to reply
 

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