您的位置:首页 > 其它

[Leetcode 87] 29 Divide Two Integers

2013-07-25 08:27 447 查看
Problem:

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

Analysis:

I think the problem wants us to use binary search to find the answer instead of simply using some arithmetic operations. So the binary search version comes first. When dealing with it, pay attention to the extrame test cases such (1<<31) and (1<<31)-1, these limit case may be wrong if the int type is chosen. A simple way to fix it is to use the long long type and then convert in back to int when returning the result. Also, the positive or negative value should be considered too.

If we really can't use any such operations, then the only tool we have is bit operation. Using << to double the divisor we have, find the max number that is less than or equal to the dividend. Keep record of the number of shifts we have made and substrct the shiftted number from the dividend, and repeat this process until the dividend is 1 or 0. Sum all these number of shift up and we can also get the answer. There are so many details to care about in this version.

Code:

Binary Search Version:

class Solution {
public:
int divide(int dividend, int divisor) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

long long dd = dividend, di = divisor;

bool isNeg = false;

if (dd < 0) { dd = -dd; isNeg = !isNeg; }
if (di < 0) { di = -di; isNeg = !isNeg; }

long long res = 0;
while (true) {
int sft;
for (sft=0; (di<<sft)<dd; sft++)
;

if ((di<<sft) == dd)
return isNeg ? -((1<<sft) + res) : ((1<<sft) + res);
else if (di > dd)
return isNeg ? -res : res;
else{
dd -= (di<<(sft-1));
res += (1<<(sft-1));
}
}

return res;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: