7. 整数反转
- 题号:7
- 来源:LeetCode
- 难度:中等
- 标签:
数学字符串 - 语言:TypeScript
- 解法:1 个
- 作者:lmliheng
- 最近更新:2026-09-27
TypeScript · O(log n) 时间 · O(log n) 空间 · 更新于 2026-09-27
转字符串反转去尾零,BigInt判溢出
typescript
/**
* @difficulty medium
* @tags 数学,字符串
* @time O(log n)
* @space O(log n)
* @note 转字符串反转去尾零,BigInt判溢出
* @7. 整数反转
*/
// 去除末尾0: str.replace(/0+$/, '');
/**
*
* @字符串方法
*
*/
function reverse(x: number): number {
let isPositive = x > 0 ? 1 : 0
let x_str = isPositive ? x.toString() : x.toString().slice(1)
x_str = x_str.replace(/0+$/, '').split("").reverse().join('')
let res = isPositive ? BigInt(x_str) : -BigInt(x_str)
if (res >= 2147483648 || res < -2147483648) {
return 0
}
return Number(res)
};
/**
* @应该使用数字方法
*/在 GitHub 上查看题目所在目录:lmliheng/algorithm