Divide Two Integers

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

class Solution {
public:
     int divide( int dividend,  int divisor) 
    {
         long  long  int a=dividend< 0? 0-( long  long)dividend:dividend;
         long  long  int b=divisor< 0? 0-( long  long)divisor:divisor;

         int result= 0;
         long  long  int ones= 1;
         while((b<< 1)<=a) 
        {
            b=(b<< 1);
            ones=(ones<< 1);
        }
        
         while(ones> 0)
        {
             if(b<=a)
            {
                a=a-b;
                result=result+ones;
            }
            b=(b>> 1);
            ones=(ones>> 1);
        }
        
         if((dividend>= 0 && divisor<= 0)||(dividend<= 0 && divisor>= 0)) result= 0-result;
         return result;
    }
};  

你可能感兴趣的:(Integer)