LeetCode/reverse-integer/js/index.js

58 lines
1.1 KiB
JavaScript
Raw Normal View History

2019-11-25 10:05:59 -06:00
/*
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));