Skip to content

Commit

Permalink
feat: JavaScript solution to No. 7 Reverse Integer
Browse files Browse the repository at this point in the history
  • Loading branch information
7thPorter committed Jul 6, 2022
1 parent 5c3d533 commit 8252d8a
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions javascript/7-Reverse-Integer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @param {number} x
* @return {number}
*/
const reverse = function (x) {
const max = 2 ** 31 - 1;
const min = -(2 ** 31);

let result = 0;
while (x !== 0) {
const digit = x % 10;
x = Math.trunc(x / 10);

if (result > max / 10 || (result === max / 10 && digit >= max % 10)) {
return 0;
} else if (
result < min / 10 ||
(result === max / 10 && digit <= min % 10)
) {
return 0;
} else {
result = result * 10 + digit;
}
}

return result;
};

0 comments on commit 8252d8a

Please sign in to comment.