Question:
Given a 32-bit signed integer, reverse digits of an integer.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2, 2− 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Example:
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
Solution:
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
let arr = (Math.abs(x)+'').split('');
arr.reverse();
let result = arr.join('');
if (x < 0) {
result = '-'+result - 0;
}else{
result = result - 0;
}
if (result > Math.pow(2,31) - 1 || result < -Math.pow(2,31)) return 0;
return result;
};
Runtime: 100 ms, faster than 56.92% of JavaScript online submissions for Reverse Integer.