Skip to content

Commit 2819b62

Browse files
committed
07 initial
1 parent 886e500 commit 2819b62

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

07-Reverse-Integer.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number} x
3+
* @return {number}
4+
*/
5+
var reverse = function (x) {
6+
let rev = 0;
7+
const INT_MAX = 2147483647; // 2^31 - 1
8+
const INT_MIN = -2147483648; // -2^31
9+
10+
while (x !== 0) {
11+
let pop = x % 10; // extract last digit
12+
x = Math.trunc(x / 10); // remove last digit
13+
14+
// Check overflow before multiplying
15+
if (
16+
rev > Math.trunc(INT_MAX / 10) ||
17+
(rev === Math.trunc(INT_MAX / 10) && pop > 7)
18+
)
19+
return 0;
20+
if (
21+
rev < Math.trunc(INT_MIN / 10) ||
22+
(rev === Math.trunc(INT_MIN / 10) && pop < -8)
23+
)
24+
return 0;
25+
26+
rev = rev * 10 + pop;
27+
}
28+
29+
return rev;
30+
};

0 commit comments

Comments
 (0)