LeetCode/reverse-integer/nodejs/index.js

63 lines
1.3 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.
*/
const { assert } = require('../../util/js');
2019-11-25 10:05:59 -06:00
/**
* @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;
sol = 321;
assert(reverse(x) === sol, 'Output: 321');
2019-11-25 10:05:59 -06:00
/* Test Case 2
* Input: -123
* Output: -321
*/
x = -123;
sol = -321
assert(reverse(x) === sol, 'Output: -321');
2019-11-25 10:05:59 -06:00
/* Test Case 3
* Input: 120
* Output: 21
*/
x = 120;
sol = 21;
assert(reverse(x) == sol, 'Output: 21');