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, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333…) = 3.
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.
题意:不用乘除法,计算出两数相除的结果。除数和被除数都为32位有符号整数,除数不为0,结果溢出返回 2^31 − 1.
思路:利用位运算,简单来说被除数每次减去除数,计算减的次数。
具体实现:以被除数div 大于等于除数dis 为前提,在数t = dis 每次乘2,即左移一位都大于被除数,则计数扩大两倍,t也扩大两倍,这个循环结束后,总的计数res更新,被除数div 也更新 div=div-t,即减去内循环中的倍数个除数,接着再次进行循环判断。
class Solution {
public:
int divide(int dividend, int divisor) {
int flag = dividend > 0 ^ divisor > 0 ? -1 : 1;
long long div = labs(dividend),dis = labs(divisor);
long res=0;
while(div >= dis)
{
long t=dis,count = 1;
while(div > t<<1)
{
t<<=1;
count<<=1;
}
res+=count;
div-=t;
}
res = flag*res;
return res>INT_MAX?INT_MAX:res;
}
};