05 August 2008
Given two integers
and 1
dividend
, divide two integers without using multiplication, division and mod operator.1
divisor
Return the quotient after dividing
by 1
dividend
.1
divisor
The integer division should truncate toward zero.
Example 1:
1
2
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
1
2
Input: dividend = 7, divisor = -3
Output: -2
Note:
不让用乘法除法和取余,来实现地板除法,那就只好用位操作了,参考了这里的解法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int divide(int dividend, int divisor) {
boolean isNegative = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) ? true : false;
long absDividend = Math.abs((long) dividend);
long absDivisor = Math.abs((long) divisor);
long result = 0;
while (absDividend >= absDivisor) {
long temp = absDivisor, count = 1;
while (temp <= absDividend) {
temp <<= 1;
count <<= 1;
}
result += count >> 1;
absDividend -= temp >> 1;
}
return isNegative ? (int) ~result + 1 : (result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) result);
}
}