Problem
Given two integers dividend
and divisor
, divide two integers without using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345
would be truncated to 8
, and -2.7335
would be truncated to -2
.
Return the quotient after dividing dividend
by divisor
.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]
. For this problem, if the quotient is strictly greater than 2^31 - 1
, then return 2^31 - 1
, and if the quotient is strictly less than -2^31
, then return -2^31
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using Binary Shifts
We know:
|
|
We need to find the quotient given the divisor and dividend.
Any number can be represented in binary form:
|
|
Same goes for quotient
. Let us have an example: 58/5
:
58 = (11) * 5 + 3
In binary, this quotient is ( $(11)_{10} = (1011)_2$ ):
|
|
We are given the equation 58 = q * 5 + rem
and need to find q
.
First, multiply 5 by powers of 2 until the result exceeds the dividend. Since multiplication operator is not allowed, we use bitwise left shift for multiplication:
|
|
We observe that:
|
|
You can see we are getting close to the equation we initialy wanted (eqa II).
Since 5 is multiplied by (2^3), we add (2^3) to our answer and update the dividend:
|
|
Further operating on equation III:
|
|
What we effectively have done is, subtracted the result we got from our first step from dividend (58 - 40)
.
We arived at the same question again but with a smaller dividend this time.
dividend = 18, divisor = 5
Therefore let us repeat the process:
|
|
We add 2^1 to our answer. Looking back:
|
|
You can notice we are gradually advancing towards equ II: Our new dividend is now:
|
|
dividend = 8, divisor = 5
Repeating the process:
|
|
We add 2^0 to our answer. New dividend:
|
|
dividend = 3, divisor = 5
At this step, we stop iterating as our dividend is less than the divisor (we have also found our remainder = 3, as 5 should be multiplied with 0 and what remains is the remainder).
Looking back again for the last time:
|
|
In the process, we have finally reached the equation we wanted to, and have got the answer as:
|
|
Code
|
|
Complexity
- ⏰ Time complexity:
O(log n)
- 🧺 Space complexity:
O(1)