7.整数反转
小于 1 分钟
7.整数反转
/*
* @lc app=leetcode.cn id=7 lang=typescript
*
* [7] 整数反转
*/
// @lc code=start
function reverse(x: number): number {
let s: string = String(x);
if (s.endsWith("0")) {
s = s.substring(0, s.length - 1); // 左闭右开
}
// 对s进行反转
let arr = s.split("");
let l = 0,
r = arr.length - 1;
while (l <= r) {
if (arr[l] == "-") {
l++;
} else {
[arr[l], arr[r]] = [arr[r], arr[l]];
l++;
r--;
}
}
let res = Number(arr.join(""));
return Math.abs(res) > Math.pow(2, 31) ? 0 : res;
}
console.log(reverse(12301));
// @lc code=end
Loading...
