题目描述
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Note:
Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
思路
考察位运算。注意边界判断。
参考:https://blog.csdn.net/qq508618087/article/details/50707159
代码
class Solution {
public:
int divide(int dividend, int divisor) {
if (dividend == 0) return 0;
if (divisor == 1) return dividend;
long long num1 = labs(dividend);
long long num2 = labs(divisor);
long long ans = 0;
while(num2 <= num1) {
int cnt = 1;
while((num2 << cnt) <= num1) cnt++;
ans += (1<<(cnt-1));
num1 -= (num2 << (cnt-1));
}
if (ans < 0) return INT_MAX;
ans = ((dividend>0) ^ (divisor>0)) ? -ans : ans;
if (ans > INT_MAX || ans < INT_MIN) return INT_MAX;
return ans;
}
};