/**
* @program: algorithm
* @description:
* @author: zkx
* @create: 2022-08-01 22:22
**/
public class LeetCode29 {
public static void main(String[] args) {
LeetCode29 l = new LeetCode29();
System.out.println(l.divide(-2147483648, -1));
}
public int divide(int dividend, int divisor) {
//被除数 = 0 或 除数=1 的情况 商的返回值
if (dividend == 0 || divisor == 1) {
return dividend;
}
//当 除数 = -1 时
if (divisor == -1) {
//数值范围[-2^31,2^31-1] 此处为了避免 被除数 = -2^31 因除数=-1 商 = 2^31 越界的情况
if (dividend > Integer.MIN_VALUE) {
return -dividend;
}
return Integer.MAX_VALUE;
}
long a = dividend;
long b = divisor;
int sign = 1;
//sign 作为标志位 表示 商的正负号
if ((a > 0 && b < 0) || (a < 0 && b > 0)) {
sign = -1;
}
//将 a,b 变为正数
a = a > 0 ? a : -a;
b = b > 0 ? b : -b;
//res >= 0
long res = div(a, b);
//sign = 1 商为 正数
if (sign == 1) {
return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) res;
}
//sign = -1 商为 负数
return (int) -res;
}
//此时 a,b均为正数
public long div(long a, long b) {
//如果 被除数 < 除数 商为0
if (a < b) {
return 0;
}
/**
* 此时 被除数 > 除数 商最小 为1
下文计算方式
定义一个变量 存储 最初的除数
循环条件 除数 * 2 <= 被除数
如果 除数*2 <= 被除数
除数 = 除数*2 商 = 商*2 下一轮循环
如果 除数*2 > 被除数
被除数 = 被除数 - 除数 执行 商 + 函数名(被除数,变量)
例子
定义一个变量 = 最初的除数
20 / 3
3+3 = 6 6 < 20
2 = 1+1
下一轮循环
6 + 6 = 12 12 < 20
4 = 2+2
下一轮循环
12+12 = 24 24 > 20
20-12 = 8
执行 递归 4 + 函数名(8,3)
最终结果 商 = 4 + 2 = 6
**/
//定义count 作为商
long count = 1;
long tb = b;
while ((tb + tb) <= a) {
count = count + count;
tb = tb + tb;
}
return count + div(a - tb, b);
}
}
剑指 Offer II 001. 整数除法 Java解法
于 2022-08-02 08:57:09 首次发布