Description:
Reverse digits of an integer.
Example1: x = 123, return 321Example2: x = -123, return -321
click to show spoilers.
**Note:
**The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
My code:
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
let str = x.toString();
if(x >= 0) {
var temp = parseInt(str.split("").reverse().join(""));
if(temp >= Math.pow(2, 31)) {
return 0;
} else {
return temp;
}
} else {
var temp = str.slice(1, str.length).split("").reverse().join("");
if(temp > Math.pow(2, 31)) {
return 0;
} else {
return parseInt("-" +temp);
}
}
};
Note: 主要是要了解IEEE 754格式带符号整数的取值范围是-2^31~2^31-1
,对已经反序的数字判断,不在范围就返回0即可