return x/y
11/1
在Java当中, 由于只有int而没有long, 所以存在一个很烦躁的问题,就是最小的数字的相反数比最大的数字要大, 举个栗子, 假设Java里的int都是4位,那么最大数是0b111,写作0b0111, 而-1是0b1111, 最小数写作0b1000, 可以看到最大数是7, 而最小数是8, 所以x=Integer.min要作为一个特殊情形单独考虑
另外就是如何寻找最大的shift容易会错
public class Solution {
public int divide(int x, int y) {
// return x/y
/*
* edge cases:
* 1. x and y could be negative
* 2. if x = Integer.min, then -x overflows; have to insert 1 in the middle
* 3.
*/
boolean isNegative = false;
boolean overflow = false; // the only case is: x = Interger.min
if( y < 0){
if( y == Integer.MIN_VALUE){
return x == Integer.MIN_VALUE? 1: 0;
}else{
y = 0-y;
isNegative = !isNegative;
}
}
if(x < 0){
if( x == Integer.MIN_VALUE){
x = Integer.MAX_VALUE;
overflow = true;
}else{
x = 0-x;
}
isNegative = !isNegative;
}
// now that x > 0, y > 0
// treat x and y as binary
if( x < y) return 0;
int ans = 0;
while( x >= y){
int shift = maxShift(x,y);
ans += (1<<shift);
x -= (y<<shift);
if(overflow){
x++;
overflow = false;
}
}
return isNegative?(0-ans):ans;
}
private int maxShift(int x,int y){
// find max shift s.t. (x<<shift) < y
int prev = (y<<0);
int shift = 0;
for(; shift <31; shift ++){
int mask = (y<<shift);
if(mask > x) break;
if(mask < prev) break; // err1: how to examine if it is too much shift?
// for example, suppose 4-bit digit, x = 0b1101, y = 0b100, y<<1 = 0b1000 < x, but y<<2 overflows!
prev = mask;
}
return shift-1;
}
}
空间复杂度是O(1)
时间复杂度也是固定的, 因为一共是32位, 最极端的栗子是x=Integer.max, y = 1, 那么一共需要的操作是32*32, 本质上来说也是O(1)的操作