Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
public class Solution {
public int divide(int dividend, int divisor) {
int r = 0;
if (divisor == 0) {
return 0;
}
if (dividend == Integer.MIN_VALUE && divisor == Integer.MIN_VALUE) {
return 1;
} else if (divisor == Integer.MIN_VALUE) {
return 0;
} else if (dividend == Integer.MIN_VALUE) {
if (divisor == -1) {
return Integer.MAX_VALUE;
}
int res = div(add(dividend, 1), divisor);
return add(res, div(minus(dividend, multi(res, divisor)), divisor));
} else {
return div(dividend, divisor);
}
}
private int minus(int a, int b) {
// TODO Auto-generated method stub
return add(a, negNum(b));
}
private int multi(int a, int b) {
// TODO Auto-generated method stub
int res = 0;
while (b != 0) {
if ((b & 1) != 0) {
res = add(res, a);
}
a <<= 1;
b >>>= 1;
}
return res;
}
private int div(int a, int b) {
// TODO Auto-generated method stub
int x = isNeg(a) ? negNum(a) : a;
int y = isNeg(b) ? negNum(b) : b;
int res = 0;
for (int i = 31; i > -1; i = minus(i, 1)) {
if ((x >> i) >= y) {
res |= (1 << i);
x = minus(x, y << i);
}
}
return isNeg(a) ^ isNeg(b) ? negNum(res) : res;
}
private int negNum(int a) {
// TODO Auto-generated method stub
return add(~a, 1);
}
private boolean isNeg(int a) {
// TODO Auto-generated method stub
return a < 0;
}
private int add(int a, int b) {
// TODO Auto-generated method stub
int sum = a;
while (b != 0) {
sum = a ^ b;
b = (a & b) << 1;
a = sum;
}
return sum;
}
}
public class Solution {
public int divide(int dividend, int divisor) {
if (dividend == 0 || divisor == 0) {
return 0;
}
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
boolean isNeg = (dividend > 0 && divisor < 0)
|| (dividend < 0 && divisor > 0);
long a = Math.abs((long) dividend);
long b = Math.abs((long) divisor);
if (b > a) {
return 0;
}
long sum = 0;
long pow = 0;
int result = 0;
while (a >= b) {
pow = 1;
sum = b;
while (sum + sum <= a) {
sum += sum;
pow += pow;
}
a -= sum;
result += pow;
}
return isNeg ? -result : result;
}
}
本文介绍了一种不使用乘法、除法和取余运算符实现整数除法的方法。通过位操作和循环实现了除法功能,并考虑了溢出情况。
506

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



