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 thedividentis 32 anddivisoris 3. Left shift one time,divisorbecomes 6; left shift two time, it becomes 12; left shift three times, it becomes 24; left shift four times, it becomes 48. Now thedivisoris greater than thedivident, so we need left shift 3 times to keep thedivisorless thandivident, and theres = 2^3=8. If we left shift 3 times, thedivisoris 24, we usedividentsubtract it, we get the newdivident = 32-24 = 8. Repeat the same step withdivident=8anddivisor=3. Now, we can only left shift 1 times since3*2=6<8, andreswill be2^1=2, so we getres = 8+2 = 10.
Solution
1 | |