【LeetCode 29】Divide Two Integers

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

If it is overflow, return MAX_INT.

题意:

  实现除法,但不允许用乘、除、以及取模运算。

思路:

  一下一下减必然显得很low,事实上可以第一次用 dividend 减 divisor,第二次用 dividend - divisor 减 2 * divisor,第三次用 dividend - 3 * divisor 减 4 * divisor... 直到减不下去了,那么此时再乖乖的用dividend - (x = 1+2+4+...+2^n) * divisor 减 divisor,dividend - (x+1) * divisor 减 2 * divisor... 循环往复,计好数就ok啦。这道题有个特殊的trick,网上很多accept的代码我再提交已经过不去了(很好奇当年他们怎么过的。。。),只能默默地手动判断了。

C++:

 1 class Solution {

 2 public:

 3     int divide(int dividend, int divisor) {

 4         

 5         if(dividend == 0 || divisor == 0)

 6             return 0;

 7         //特殊判断,超过最大值应返回MAX_INT

 8         if(dividend == -2147483648 && divisor == -1)

 9             return 2147483647;

10         

11         long long a = abs(static_cast<long long>(dividend));

12         long long b = abs(static_cast<long long>(divisor));

13         long long ret = 0;

14         

15         while(a >= b)

16         {

17             long long c = b;

18             

19             for(int i = 0; a >= c; i++)

20             {

21                 a -= c;

22                 c <<= 1;

23                 ret += 1 << i;

24             }

25         }

26         return ((dividend ^ divisor) >> 31) ? (-ret) : (ret);

27     }

28 };

 

你可能感兴趣的:(LeetCode)