题目:
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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 2^31 − 1 when the division result overflows.
描述:
给出被除数和除数,要求不使用乘法、除法和取模运算符,求出商,
其中除数不为0,如果商超过int的范围,则返回边界值
分析:
猜到是模拟二进制的除法,但是确实不知道怎么下手求,原先自己的思路是利用类似快速幂的形式进行叠乘,能解决一部分问题,但是对于两个数的绝对值比较接近的情况会超时,后来参看了大神的博客(链接点这里),发现自己还是太弱了,需要继续学习,其实也完全想过这种手动模拟的方法,可惜没有具体去实现,
另外,参考的博客代码也好像有点bug,因为对于某些数据64位整数也会溢出,建议使用无符号64位整数,不得不佩服后台数据的设计,边界把握的很好
来几组数据:
1026117192
-874002063
1004958205
-2137325331
-2147483648
-1
7
-3
10000
2
100
2
10
1
10
3
10
5
10
6
10
8
10
10
10
20
代码:(时间复杂度 O( log n)
class Solution {
public:
int divide(int dividend, int divisor) {
int sign = (dividend > 0) == (divisor > 0) ? 1 : -1;
long long result = 0, a = abs(dividend), b = abs(divisor);
while (a >= b) {
unsigned long long temp = b, base = 1;
while (temp << 1 < a) {
temp <<= 1;
base <<= 1;
}
a -= temp;
result += base;
}
result = sign * result;
if (result > INT_MAX || result < INT_MIN) {
result = INT_MAX;
}
return (int)result;
}
long long abs(long long x) {
return x > 0 ? x : - x;
}
};