feat: Added reverse-integer js
This commit is contained in:
parent
65186a36a1
commit
92d67c5201
57
reverse-integer/js/index.js
Normal file
57
reverse-integer/js/index.js
Normal file
@ -0,0 +1,57 @@
|
||||
/*
|
||||
Given a 32-bit signed integer, reverse digits of an integer.
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: 123
|
||||
Output: 321
|
||||
Example 2:
|
||||
|
||||
Input: -123
|
||||
Output: -321
|
||||
Example 3:
|
||||
|
||||
Input: 120
|
||||
Output: 21
|
||||
Note:
|
||||
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number} x
|
||||
* @return {number}
|
||||
*/
|
||||
const reverse = function(x) {
|
||||
const MAX_INT = Math.pow(2,31) -1;
|
||||
const MIN_INT = Math.pow(2,31)* -1;
|
||||
|
||||
const X = x.toString();
|
||||
|
||||
const isNeg = X[0] === '-';
|
||||
let reverseIntegerString = X.split('').reverse().join('');
|
||||
|
||||
const reverseInteger = isNeg ? parseInt(reverseIntegerString) * -1 : parseInt(reverseIntegerString);
|
||||
|
||||
return (reverseInteger >= MAX_INT || reverseInteger <= MIN_INT) ? 0 : reverseInteger;
|
||||
};
|
||||
|
||||
/* Test Case 1
|
||||
* Input: 123
|
||||
* Output: 321
|
||||
*/
|
||||
x = 123;
|
||||
console.log(reverse(x));
|
||||
|
||||
/* Test Case 2
|
||||
* Input: -123
|
||||
* Output: -321
|
||||
*/
|
||||
x = -123;
|
||||
console.log(reverse(x));
|
||||
|
||||
/* Test Case 3
|
||||
* Input: 120
|
||||
* Output: 21
|
||||
*/
|
||||
x = 120;
|
||||
console.log(reverse(x));
|
Loading…
Reference in New Issue
Block a user