Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 474b112

Browse files
committedDec 30, 2021
Add solution #29
1 parent bc60a46 commit 474b112

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium|
2929
27|[Remove Element](./0027-remove-element.js)|Easy|
3030
28|[Implement strStr()](./0028-implement-strstr.js)|Easy|
31+
29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium|
3132
31|[Next Permutation](./0031-next-permutation.js)|Medium|
3233
33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium|
3334
34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium|

‎solutions/0029-divide-two-integers.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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

Comments
 (0)
Please sign in to comment.