LeetCode: Divide Two Integers Solution

Approach

Use log identities (easy to understand)

1log(a/b) = log(c)
2=> log(a) - log(b) = log(c)
3=> e^(log(a) - log(b)) = c

Implementation

1/**
2 * @param {number} dividend
3 * @param {number} divisor
4 * @return {number}
5 */
6var divide = function (dividend, divisor) {
7 const MIN_INT = -Math.pow(2, 31)
8 const MAX_INT = Math.pow(2, 31) - 1
9 const sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1
10
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 *= sign
16 res = Math.min(res, MAX_INT)
17 res = Math.max(res, MIN_INT)
18
19 return res
20}

Comments

Loading comments...

Tags

leetcode

math

bit manipulation

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Equal Sum Arrays With Minimum Number Of Operations

Feb 28, 2021

Previous Post

HoningJS

Search Posts