Divide two integers without using multiplication, division and mod operator.
If it will overflow(exceeding 32-bit signed integer representation range), return 2147483647
The integer division should truncate toward zero.
Example
Example 1:
Input: dividend = 0, divisor = 1
Output: 0
Example 2:
Input: dividend = 100, divisor = 9
Output: 11
思路:基本思路是利用减法, 看看被除数可以减去多少次除数. 使用倍增的思想优化
class Solution {
public int divide(int dividend, int divisor) {
if(dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
int a = Math.abs(dividend);
int b = Math.abs(divisor);
int res = 0;
while(a - b >= 0) {
int temp = b;
int count = 1; // 注意count是从1开始的;否则shift全是0;
while(a - (temp << 1) >= 0) {
temp = temp << 1;
count = count << 1;
}
a -= temp;
res += count;
}
return dividend > 0 == divisor > 0 ? res : -res;
}
}