整数反转

逐位翻转,如果是负数,特殊处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {number} x
* @return {number}
*/
var reverse = function (x) {
let newX = 0;
const isNegative = x < 0;
while (x) {
const num = x % 10;
newX *= 10;
newX += num;
x = isNegative ? Math.ceil(x / 10) : Math.floor(x / 10);
}
if (newX > Math.pow(2, 31) - 1 || newX < -Math.pow(2, 31)) {
return 0;
}
return newX;
};
// console.log(reverse(-123));

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。