Saturday, September 20, 2014

LeetCode: Divide Two Integers

Divide two integers without using multiplication, division and mod operator.


   int divide(int dividend, int divisor) {  
     long long x = abs((long long)divisor);  
     long long y = abs((long long)dividend);  
     long long res = 0, sum = x, negative = 0 , q = 1;  
   
     if (divisor < 0 && dividend < 0)negative = 0;  
     else if (divisor < 0 || dividend < 0)negative = 1;  
   
     if(x>y)return 0;  //y/x  
   
     while(sum)  
     {  
       if (sum << 1 <= y)  
       {  
         sum = sum<<1;  
         q = q<<1;  
       }  
       else  
       {  
         res += q;  
         if(y - sum < x) sum = 0;  
         else {  
           y = y - sum;  
           sum = x;  
           q = 1;  
         }  
       }  
     }  
     if(negative)  
       res = -res;  
   
     return (int)res;  
   }  

No comments:

Post a Comment