我的回答
function reverse(x: number): number {
const min = Math.pow(-2, 31);
const max = Math.pow(2, 31) - 1;
if (x === 0) return x;
const sign = x >= 0 ? "+" : "-";
const s = String(Math.abs(x)).split("").reverse().join("");
const res = Number(sign + s);
if (res < min || res > max) return 0;
return res;
}
其他回答
function reverse(x: number): number {
let res = 0;
const min = Math.pow(-2, 31);
const max = Math.pow(2, 31) - 1;
while (x) {
res = res * 10 + (x % 10);
if (res < min || res > max) return 0;
x = ~~(x / 10);
}
return res;
}