The task is taken from leetcode
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321Example 2:
Input: -123 Output: -321Example 3:
Input: 120 Output: 21Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
My solution
/**
* @param {number} x
* @return {number}
*/
const reverse = x => {
if (x === undefined || x === null) { return; }
if (x < 10 && x >= 0) { return x; }
const num = [];
const dissectNum = n => {
if (n <= 0) { return; }
const y = n % 10;
num.push(y);
return dissectNum(Math.floor(n / 10));
};
dissectNum(Math.abs(x));
let tmp = 0;
const maxPow = num.length - 1;
for (let i = 0; i < num.length; i++) {
tmp += num[i] * Math.pow(10, maxPow - i);
}
const result = (x < 0 ? -1 : 1 ) * tmp;
return result > Math.pow(-2, 31) && result < (Math.pow(2, 31) - 1)
? result
: 0;
};