8ms solution inspired by calculate binary division by hand


  • 0
    P
    class Solution {
    public:
        int divide(int dividend, int divisor) {
            if(dividend == INT_MIN){
                if(divisor==-1)return INT_MAX;
                if(divisor==1)return INT_MIN;
                
                if(divisor<0)return 1+divide(INT_MIN-divisor,divisor);
                
                return -1+divide(INT_MIN+divisor,divisor);
            }
            if(divisor==INT_MIN)return 0;
            
            if(!divisor)return INT_MAX;
            
            if(dividend<0)
                if(divisor<0)
                    return divide(-dividend,-divisor);
                else
                    return -divide(-dividend,divisor);
            
            if(divisor<0)
                return -divide(dividend,-divisor);
                
            if(dividend<divisor)return 0;
          
            int temp1=dividend,temp2=divisor,res=0,k;
            
            while(temp1 >= divisor){
                k=0;
                temp2=divisor;
                
                while(temp2<=temp1 && temp2<(INT_MAX>>1)){
                    k++;
                    temp2= (temp2<<1);
                }
                
                if(temp2>temp1){
                    temp1 -= (temp2>>1);
                    res += (1<<(k-1));
                }else{
                    temp1 -= temp2;
                    res += (1<<k);
                }
            }
                
            return res;
        }
    };

Log in to reply
 

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