My log(32), O(1) 8ms solution with comments in C++


  • 1
    W

    class Solution {
    public:
    // should pay a great attension to INT32_MIN.
    // -INT32_MIN is useless.
    // 这里需要特别注意 INT32_MIN, 对于 INT32_MIN来说, 取对应的正数是没用的。 当返回值为 INT32_MIN时,也是一样。

    int static divide(int dividend, int divisor) {
        if(divisor==0) return INT32_MAX;
        if(dividend==INT32_MIN && divisor==-1) return INT32_MAX;
        bool flag = true;
        if((dividend>0 && divisor<0) || (dividend<0 && divisor>0)){
            flag = false;
        }
        // should be long ,should not use abs.
        long ldividend = dividend<0 ? -(long)dividend : dividend;
        long ldivisor =  divisor<0? -(long)divisor: divisor;
        if(ldivisor>ldividend) return 0;
        // should be long
        long ret = 0;
        int start = 0, end = 30;
        while(start<=end){
            int mid = (end+start)>>1;
            if(((long)(ldivisor<<mid))>ldividend){
                end = mid-1;
            } else {
                ldividend = ldividend - (ldivisor<<mid);
                ret = ret + (1<<mid);
            }
        }
        return flag ? (int)ret : (int)-ret;
    }
    

    };


  • 0
    H

    you have used division operator, which is not supposed.


  • 0
    W

    @Hmoon oh,I am sorry. I have fix that.


Log in to reply
 

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