Problem
Problem page: https://leetcode.com/problems/divide-two-integers/
Topics: Math, Binary Search
Difficulty: Medium
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Analysis
The problem doesn't allow multiplication, division or modulo, so I just use shifts, addition and subtraction. I keep track of the sign separately and use absolute values in the loop. I keep doubling the divisor by shifting it left one bit each time, and I double sub_result along with it to keep track of the multiple. Once another doubling would exceed the remaining dividend (dividend_now), I subtract the shifted divisor from it and add sub_result to result. If dividend_now is still at least as big as the original divisor, I go another round. I just drop the final remainder since it's smaller than the divisor, so the result is truncated toward zero.
Both inputs are 32-bit signed integers. Dividing by 1 leaves the dividend unchanged. A divisor with an absolute value of at least 2 gives a quotient with an absolute value of at most 1073741824, so neither case overflows. Dividing by -1 negates the dividend, and only -2147483648 becomes 2147483648, which is outside the 32-bit signed integer range. The problem says to return MAX_INT on overflow. Python integers don't overflow on their own, so I have to check for this case myself or I'll return that out-of-range result.
After each subtraction, the remaining dividend is smaller than the number I just subtracted, so the next round takes at least one fewer doubling. With q as the absolute value of the quotient, I get at most about log q rounds. Even the longest round takes at most about log q doublings, so the time complexity is O(log² q).
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-divide-two-integers/
