LeetCode/exercises/reverse-integer/nodejs/index.js

63 lines
1.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
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');
/**
* @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');
/* Test Case 2
* Input: -123
* Output: -321
*/
x = -123;
sol = -321
assert(reverse(x) === sol, 'Output: -321');
/* Test Case 3
* Input: 120
* Output: 21
*/
x = 120;
sol = 21;
assert(reverse(x) == sol, 'Output: 21');