通过加减法、移位实现整数乘、除法(仅仅保留商)
1. 先导
计算机中,整数的乘法、除法、取模、取余的计算底层均是使用 移位 + 加减法
实现,基于此,我们来实现 32 位的整数乘除法
2. 非负整数的乘除法
2.1 乘法
32 位的乘法,最大值相乘不会超过 64 位,无论是否有符号,但是两个 int
类型的数相乘,结果不会超过 64 位,故使用 64 位的 long
保留结果
// 方法1:仅仅通过加法进行实现乘法
// 缺点:耗时长
public long plus1(int multiplier, int multiplicand) {
if(multiplier == 0 ^ multiplicand == 0) {
return 0;
}
int count = Math.min(multiplier,multiplicand);
int num = Math.max(multiplier,multiplicand);
long res = 0;
for(int i = 0; i < count;i++) {
res += num;
}
return res;
}
// 方法2:通过移位实现乘法
// 缺点:初见难以理解
public long plus2(int multiplier, int multiplicand) {
if(multiplier == 0 ^ multiplicand == 0) {
return 0;
}
long res = 0;
while(multiplier > 0) {
if((multiplier & 1) == 1) {
res += multiplicand;
}
// 乘数右移 被乘数左移 或者 乘数左移 被乘数左移
multiplicand <<= 1;
multiplier >>= 1