End of Year Sale: Use Coupon Code END2025 to Get Extra 25% Off.
00DAYS
:
00HOURS
:
00MINUTES
:
00SECONDS
Leetcode Problem 29. Divide Two Integers
29. Divide Two Integers
Leetcode Solutions
Approach: Adding Powers of Two with Bit-Shifting
Handle edge cases where the result would overflow the 32-bit signed integer range.
Convert both dividend and divisor to negative numbers to avoid overflow issues.
Initialize variables to keep track of the highest double of the divisor and its corresponding power of two.
Repeatedly double the divisor and increment the power of two until the divisor is greater than the dividend.
Initialize the quotient to zero.
While the dividend is greater than or equal to the divisor:
a. If the dividend is greater than or equal to the highest double, subtract the highest double from the dividend and add the corresponding power of two to the quotient.
b. Right-shift the highest double and the corresponding power of two to get the next lower double and power of two.
If the original dividend and divisor had different signs, negate the quotient.