题源剑指offer
在代码中,没有对整数的边界进行判断。读者可自行添加条件。唯一需要注意的就是,整数的最大正数是要比最小负数的绝对值大 1 的。所以要避免,溢出。
package 剑指Offer.整数除法和二进制加法;
/**
* @program:多线程和IO
* @descripton:输入两个int型整数,它们将进行除法计算并返回商,要求不用
* @乘号除号及求余符号。当发生溢出时,返回最大的整数值。除数不为0.
* @author:ZhengCheng
* @create:2021/9/21-20:27
**/
public class IntegerDivide {
public static void main(String[] args) {
int a = -120;
int b = 2;
System.out.println(new IntegerDivide().DivideWhile(a,b));
System.out.println(new IntegerDivide().DivideTwoTimes(a,b));
}
//解法1:使用循环除法
public int DivideWhile(int a ,int b){
int negative = 0 ;
if (a < 0){
a = -a;
negative++;
}
if (b < 0){
b = -b;
negative++;
}
int cnt = 0;
while ( a- b >= 0){
a -= b;
cnt ++;
}
return negative == 1? -cnt:cnt;
}
//优势:简单 劣势:时间复杂度过高,如果一个数很大的话,其运算次数过多
//解法2:通过2倍2倍的判断,这样减少时间复杂度。
public int DivideTwoTimes(int a ,int b){
int negative = 0;
if (a < 0){
a = -a;
negative++;
}
if (b < 0){
b = -b;
negative++;
}
int cnt = 0;
while ( a >= b){
int temp = b ;
int maxNum = 1;
while ( a > temp*2 ){
temp +=temp;
maxNum += maxNum;
}
cnt += maxNum;
a -= temp;
}
return negative == 1? -cnt:cnt;
}
}
整数除法无符号运算
本文介绍了一种不使用乘除及求余操作实现整数除法的方法,包括简单的循环除法和优化后的二倍法,有效避免了溢出问题。
1011

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



