Skip to content

Commit 19c46e4

Browse files
authored
Merge pull request neetcode-gh#372 from 7thPorter/7-reverse-integer
feat: JavaScript solution to No. 7 Reverse Integer
2 parents 8ac18b1 + 8252d8a commit 19c46e4

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

javascript/7-Reverse-Integer.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number} x
3+
* @return {number}
4+
*/
5+
const reverse = function (x) {
6+
const max = 2 ** 31 - 1;
7+
const min = -(2 ** 31);
8+
9+
let result = 0;
10+
while (x !== 0) {
11+
const digit = x % 10;
12+
x = Math.trunc(x / 10);
13+
14+
if (result > max / 10 || (result === max / 10 && digit >= max % 10)) {
15+
return 0;
16+
} else if (
17+
result < min / 10 ||
18+
(result === max / 10 && digit <= min % 10)
19+
) {
20+
return 0;
21+
} else {
22+
result = result * 10 + digit;
23+
}
24+
}
25+
26+
return result;
27+
};

0 commit comments

Comments
 (0)