# LeetCode: Divide Two Integers Solution

## Approach

Use log identities (easy to understand)

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}log(a/b) = log(c)2=> log(a) - log(b) = log(c)3=> e^(log(a) - log(b)) = c`

## Implementation

```1/**2 * @param {number} dividend3 * @param {number} divisor4 * @return {number}5 */6var divide = function (dividend, divisor) {7  const MIN_INT = -Math.pow(2, 31)8  const MAX_INT = Math.pow(2, 31) - 19  const sign = (dividend > 0) ^ (divisor > 0) ? -1 : 110
11  dividend = Math.abs(dividend)12  divisor = Math.abs(divisor)13
14  let res = Math.floor(Math.exp(Math.log(dividend) - Math.log(divisor)))15  res *= sign16  res = Math.min(res, MAX_INT)17  res = Math.max(res, MIN_INT)18
19  return res20}```

leetcode

math

bit manipulation

## Next Post

LeetCode: Equal Sum Arrays With Minimum Number Of Operations

Feb 28, 2021

Search Posts