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.
class Solution {
public:
int divide(int dividend, int divisor) {
if (!divisor || (dividend == INT_MIN && divisor == -1))
return INT_MAX;
unsigned int divd = dividend, divs = divisor;//使用unsigned防止-2147483648符号取反后溢出
if(divisor < 0)divs = -divs;//负数全部转化为正数
if(dividend < 0)divd = -divd;
int res = 0;
while(divd >= divs)
{
long long a = divs;//使用long long防止移位溢出
int i;
for(i = 0; a <= divd; i++)
a <<= 1;
res += (1 << (i-1));
divd -= (divs << (i-1));
}
return (dividend>0 ^ divisor>0) ? -res : res;
}
}
整数除法算法
本文介绍了一种不使用乘法、除法和取模运算符实现两个整数相除的算法。通过位移和累加操作高效求解商,特别针对32位有符号整数范围内的除法问题。
484

被折叠的 条评论
为什么被折叠?



