Space
Open
From Fieldwork
Scales
Archive
Bitwise division. If it's divisible by k, maybe it's divisible by 2k, then 4k, and so on.
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
# Constants for 32-bit range
MAX_INT = 2147483647
MIN_INT = -2147483648
# Edge case: Overflow
if dividend == MIN_INT and divisor == -1:
return MAX_INT
# Determine sign
negative = (dividend < 0) ^ (divisor < 0)
# Use absolute values
dividend, divisor = abs(dividend), abs(divisor)
quotient = 0
# Exponential subtraction
while dividend >= divisor:
temp_divisor = divisor
multiple = 1
# Double the divisor as much as possible
while dividend >= (temp_divisor << 1):
temp_divisor <<= 1
multiple <<= 1
# Subtract the largest found chunk
dividend -= temp_divisor
quotient += multiple
return -quotient if negative else quotientPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode