Problem
Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing
dividend by divisor
.
The integer division should truncate toward zero.
Example 1:
1 |
|
Example 2:
1 |
|
Note:
- Both dividend and divisor will be 32-bit signed integers.
- The divisor will never be 0.
- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
Explanation
-
We can use bit operation to solve this problem.
-
Initialize
res = 0
. While divident is greater or equal than the divisor, we left shift the divisor. Each time we left shift the divisor, we multiple by 2 and add to theres
. For example, if thedivident
is 32 anddivisor
is 3. Left shift one time,divisor
becomes 6; left shift two time, it becomes 12; left shift three times, it becomes 24; left shift four times, it becomes 48. Now thedivisor
is greater than thedivident
, so we need left shift 3 times to keep thedivisor
less thandivident
, and theres = 2^3=8
. If we left shift 3 times, thedivisor
is 24, we usedivident
subtract it, we get the newdivident = 32-24 = 8
. Repeat the same step withdivident=8
anddivisor=3
. Now, we can only left shift 1 times since3*2=6<8
, andres
will be2^1=2
, so we getres = 8+2 = 10
.
Solution
1 |
|