给定两个整数 a 和 b ,求它们的除法的商 a/b ,要求不得使用乘号 '*'、除号 '/' 以及求余符号 '%' 。
class Solution {
public int divide(int a, int b) {
// 如果除数为-1,被除数最小的话,直接越界
if (a == Integer.MIN_VALUE && b == -1) {
return Integer.MAX_VALUE;
}
// 设置一个结果符号参数
int negative = 2;
// 除数和被除数符号一致来进行计算
// 计算正数的除法后,再按照需要来调整正负号
// 负数转化为整数可能越界。因此将除数和被除数全转为负数,然后再去计算商
if (a > 0) {
negative--;
a = -a;
}
if (b > 0) {
negative--;
b = -b;
}
int result = divideCore(a, b);
return negative == 1 ? -result : result;
}
private int divideCore(int a, int b) {
// 结果
int result = 0;
while (a <= b) {
// value作为除数
int value = b;
//被除数最多大于除数的2的quotient倍
int quotient = 1;
//判断 value >= 0xc0000000 的原因:保证 value + value 不会溢出
//0xc0000000 是十进制 -2^30 的十六进制的表示
while (value >= 0xc0000000 && a <= value + value) {
quotient += quotient;
value += value;
}
result += quotient;
a -= value;
}
return result;
}
}