|
| 1 | +/** |
| 2 | + * 29. Divide Two Integers |
| 3 | + * https://leetcode.com/problems/divide-two-integers/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given two integers dividend and divisor, divide two integers without using multiplication, |
| 7 | + * division, and mod operator. |
| 8 | + * |
| 9 | + * The integer division should truncate toward zero, which means losing its fractional part. |
| 10 | + * For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. |
| 11 | + * |
| 12 | + * Return the quotient after dividing dividend by divisor. |
| 13 | + * |
| 14 | + * Note: Assume we are dealing with an environment that could only store integers within the |
| 15 | + * 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly |
| 16 | + * greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, |
| 17 | + * then return -231. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number} dividend |
| 22 | + * @param {number} divisor |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var divide = function(dividend, divisor) { |
| 26 | + if (divisor === -1 && dividend === Math.pow(-2, 31)) { |
| 27 | + return Math.pow(2, 31) - 1; |
| 28 | + } |
| 29 | + const isNegative = dividend > 0 ^ divisor > 0; |
| 30 | + let result = 0; |
| 31 | + |
| 32 | + dividend = Math.abs(dividend); |
| 33 | + subtract(Math.abs(divisor), 1); |
| 34 | + |
| 35 | + function subtract(n, quotient) { |
| 36 | + if (dividend > n) { |
| 37 | + subtract(n * 2, quotient * 2); |
| 38 | + } |
| 39 | + if (dividend >= n) { |
| 40 | + dividend -= n; |
| 41 | + result += quotient; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return isNegative ? -result : result; |
| 46 | +}; |
0 commit comments