剑指 Offer II 001. 整数除法
给定两个整数 a 和 b ,求它们的除法的商 a/b ,要求不得使用乘号 ‘*’、除号 ‘/’ 以及求余符号 ‘%’ 。
将正负号标志位,另外运算,
class Solution {
public int divide(int a, int b) {
//如果被除数是
if(a==Integer.MIN_VALUE&&b==-1){
return Integer.MAX_VALUE;
}
//负数标志位
boolean flag=false;
if((a<0&&b<0)||(a>0&&b>0)){
flag=true;
}
long a1=a>0?-a:a;
long b1=b>0? -b:b;
if(a1>b1){
return 0;
}
//绝对值的计算,a>b
int result=0;
int shift=31;
while(a1<=b1){
//用左移乘法加大被除数
while(a1>b1<<shift){
shift--;
}
a1-=b1<<shift;
result+=1<<shift;
}
return flag?result:-result;
}
}