整数除法(Java)
package practice.npu1;
public class TwoDiv {
public static void main(String args[]){
int dividend=-500;//被除数;
int divisor=600;//除数;
int result;//结果
result= divideFlag(dividend,divisor);//解决相除以后的结果,都转化为复数
System.out.println(dividend + "/" + divisor + "=" + result);
}
public static int divideFlag(int dividend,int divisor){
int result;//解决相除以后的结果,都转化为复数
int flagx=2;
if(dividend==0x80000000 && divisor==-1){
return 0x80000000;
}//防止溢出
if(dividend>0){
dividend=-dividend;
flagx--;
}if(divisor>0){
divisor=-divisor;
flagx--;
}
result=divideCore(dividend,divisor);//优化后的结果,时间复杂度为O(logn),结果=被除数/基数的N次方
return flagx == 1 ?- result:result;
}
public static int divideCore(int dividend,int divisor){
int result=0;
while(dividend<=divisor){
//int evenum=0;
int value=divisor;
int calnum=1;
while(value>=0xc0000000 && dividend<=value+value){
value+=value;
calnum+=calnum;//被除基数value=divisor同时翻倍,calnum-----计算一次循环中被除数中包含几个除数的标记数字
}
dividend-=value;
result+=calnum;
}
return result;
}
}