class Solution {
public int divide(int a, int b) {
if(a == Integer.MIN_VALUE){
if(b == 1){
return Integer.MIN_VALUE;
}
if(b == -1){
return Integer.MAX_VALUE;
}
}
if(b == Integer.MIN_VALUE){
if(a == Integer.MIN_VALUE){
return 1;
}else{
return 0;
}
}
if(a == 0){
return 0;
}
boolean sign = false;
if(a > 0){
a = -a;
sign = !sign;
}
if(b > 0){
b = -b;
sign = !sign;
}
int left = 1;
int right = Integer.MAX_VALUE;
int ans = 0;
while(left <= right){
int mid = left + ((right - left) >> 1);
boolean check = quickAdd(b, mid, a);
if(check){
ans = mid;
if(mid == Integer.MAX_VALUE){
break;
}
left = mid + 1;
}else{
right = mid - 1;
}
}
return sign?-ans:ans;
}
public boolean quickAdd(int y, int z, int x){
int res = 0;
int add = y;
while(z != 0){
if((z & 1) != 0){
if(res < x - add){
return false;
}
res += add;
}
if(z != 1){
if(add < x - add){
return false;
}
add += add;
}
z = z>>1;
}
return true;
}
}
剑指-001
最新推荐文章于 2024-07-25 11:27:31 发布