-
Notifications
You must be signed in to change notification settings - Fork 354
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add divideTwoIntegers algorithm
- Loading branch information
1 parent
b7c544b
commit 7af8ea2
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
// problem link: https://leetcode.com/problems/divide-two-integers/ | ||
|
||
// Runtime: 109 ms, faster than 48.23% of JavaScript online submissions for Divide Two Integers. | ||
|
||
const divide = (dividend, divisor) => { | ||
if (dividend === -2147483648 && divisor === -1) return 2147483647 | ||
let ans = 0 | ||
let sign = 1 | ||
if (dividend < 0) { | ||
dividend = -dividend | ||
sign = -sign | ||
} | ||
if (divisor < 0) { | ||
divisor = -divisor | ||
sign = -sign | ||
} | ||
if (dividend === divisor) return sign | ||
for (let i = 0, val = divisor; dividend >= divisor; i = 0, val = divisor) { | ||
while (val > 0 && val <= dividend) { | ||
val = divisor << ++i | ||
} | ||
dividend -= divisor << (i - 1) | ||
ans += 1 << (i - 1) | ||
} | ||
return sign < 0 ? -ans : ans | ||
} |