-
Notifications
You must be signed in to change notification settings - Fork 0
/
29. Divide Two Integers
32 lines (27 loc) · 1009 Bytes
/
29. Divide Two Integers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public int divide(int dividend, int divisor) {
// Handle overflow edge case
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
// Determine the sign of the result
int sign = (dividend > 0) == (divisor > 0) ? 1 : -1;
// Work with positive values for simplicity
long absDividend = Math.abs((long) dividend);
long absDivisor = Math.abs((long) divisor);
long quotient = 0;
// Subtract the divisor from the dividend using bitwise shifts
while (absDividend >= absDivisor) {
long tempDivisor = absDivisor;
long multiple = 1;
while (absDividend >= (tempDivisor << 1)) {
tempDivisor <<= 1;
multiple <<= 1;
}
absDividend -= tempDivisor;
quotient += multiple;
}
// Apply the sign to the result
return (int) (sign * quotient);
}
}