LeetCode Divide Two Integers, Feb 18 '12
难度4,出现频率3
Divide two integers without using multiplication, division and mod operator.
思路: 想到2进制还是容易的,但具体写了code,怎么也通不过online judge,于是在网上搜寻了一番,原来此题要考虑负数,溢出,不是那么容易得!
tip1: 避免溢出,先转存为更大的long long.
tip2: 先转换成正数,输出结果时检查首位是否不同,用a^b>>31得到首位
tip3: 具体的减法只要做两轮就行了,先从1->2->4..->2^k,然后2^k->...2->1,所以时间复杂度是2n = 2log_2^{a/b}.
例子:40/3:
第一轮:38-3*1-3*2-3*4 = 19 < 3*8
第二轮:17 - 3*4 - 3*1 = 2<3 over.
----------
代码如下:
int divide(int dividend, int divisor) {
long long res = 0;
int count = 1;
long long a = abs((double) dividend);
long long b = abs((double) divisor);
long long c = b;
while(a >= b){
res += count;
a -= b;
b <<= 1;
count <<= 1;
}
while(a >= c){
b >>= 1;
count = count>>1;
if(a >= b){
a -= b;
res +=count;
}
}
return ((dividend^divisor)>>31) ? (-res) : (res);
}
No comments:
Post a Comment