O(log(n)) c++


  • 0
    P
    class Solution {
    public:
        int divide(int dividend, int divisor) {
            if(!divisor) return dividend>=0? INT_MAX:INT_MIN;
            long sign1 = dividend>=0? 1:-1;    //dealing with sign
            long sign2 = divisor>=0? 1:-1;      //dealing with sign
            long d1 = sign1*(long)dividend;
            long d2 = sign2*(long)divisor;
            long ans = 0, prod = 1;
            if(d1<d2) return 0;
            while(d2 <= d1 - d2){
                d2 += d2;
                prod += prod;
            }
            while(prod){
                if(d1>=d2){
                    ans += prod;
                    d1 -= d2;
                }
                prod >>= 1;
                d2 >>= 1;
            }
            ans *= sign1*sign2;
            if(ans > INT_MAX) return INT_MAX;
            if(ans < INT_MIN) return INT_MIN;
            return (int)ans;
        }
    };
    

Log in to reply
 

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