LeetCode_Divide Two Integers

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

int divide(int dividend, int divisor) {
         int flag =1;
         if(dividend <0) flag *= -1;
         if(divisor <0)  flag *= -1;
         unsigned long long d1 = abs((long long)dividend);
         unsigned long long d2 = abs((long long)divisor);
         unsigned long long temp;
         
         if(d1 < d2)  return 0;         
         if(d1 == d2) return 1* flag;
         if(d2 == 1)  return d1* flag;
         
         unsigned long long count = 1;
         temp = d2;
         while(d1>temp){
             temp = temp<<1 ;
             count = count<<1 ;
         }
        
         int result = 0;
         while(d1 > d2){
         //下面判断中的=很关键
           while(d1 >= temp){
              d1 = d1 - temp;
              result +=  count;
           }
           temp = temp >>1;
           count = count >>1;  
         
         }
         return result*flag;
    }

这里解释下为什么必须要使用long long 才能A掉,因为计算机中的数字用补码表示,所以负数能够表示的范围比较大,去符号变正数后超过int的表示范围,所以必须使用long long 


--------------------------------------------------------------------天道酬勤!
原文地址:https://www.cnblogs.com/graph/p/2988482.html