Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
题意:不用乘除和mod运算计算两个数相除。思路:因为每个数都能表示为二进制,也就是num = a*2^0 + b*2^1....,所以我们只要去判断有哪些2^k就能相加得到结果了,第一种方式是循环,第二种写法是每次找到最大2^k,这道题就是把2换成b就是了
class Solution {
public:
int divide(int dividend, int divisor) {
long long a = abs((double)dividend);
long long b = abs((double)divisor);
long long res = 0;
while (a >= b) {
long long c = b;
for (int i = 0; a >= c; i++, c <<= 1) {
a -= c;
res += 1<<i;
}
}
int flag = ((divisor ^ dividend) >> 31) ? -1 : 1;
if (res * flag > INT_MAX)
return INT_MAX;
else return res * flag;
}
};
class Solution {
public:
int divide(int dividend, int divisor) {
long long a = abs((double)dividend);
long long b = abs((double)divisor);
long long res = 0;
while(a >= b) {
long long t = b, i = 1;
while((t << 1) < a) {
t <<= 1;
i <<= 1;
}
a -= t;
res += i;
}
int flag = ((divisor ^ dividend) >> 31) ? -1 : 1;
if (res * flag > INT_MAX)
return INT_MAX;
else return res * flag;
}
};