标签:style blog color io ar for sp div on
Divide two integers without using multiplication, division and mod operator.
分析:
不能用乘、除、取模运算,我们可以用的运算还有加、减、位运算。一个比较简单的想法是在dividend上不断减去divisor,知道余数小于divisor,然后减的次数就是所求结果。这里我们可以用类似binary search的方法用幂级跳跃试探dividend是divisor的多少倍,从而达到加速的目的。幂级跳跃又有两种方式,一种是dividend先减去divisor的1倍,另一种是dividend先减去比dividend小的divisor的最大倍数。由于乘2幂运算我们可以用位左移来实现,所以第二种方式要比第一种方式快,特别是dividend和divisor相差很多的时候。
Leetcode 通过版本:
class Solution { public: int divide(int dividend, int divisor) { long long div = (dividend > 0)? dividend:-(long long)dividend; long long dis = (divisor > 0)? divisor: -(long long)divisor; int result = 0; while(div >= dis){ int counter = 0; while(div >= dis<<counter){ counter++; } result += 1<<(counter-1); div -= dis<<(counter-1); } return ((dividend^divisor)>>31)?(-result):result; } };
超时版本:
class Solution { public: int divide(int dividend, int divisor) { long long div = (dividend > 0)? dividend:-(long long)dividend; long long dis = (divisor > 0)? divisor: -(long long)divisor; int result = 0; while(div >= dis){ long long c = dis; for(int i = 0; div >= c; i++, c<<i){ div -= c; result += 1<<i; } } return ((dividend^divisor)>>31)?(-result):result; } };
标签:style blog color io ar for sp div on
原文地址:http://www.cnblogs.com/Kai-Xing/p/4038464.html