算法(TS):整数反转

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。如果反转后整数超过 32 位的有符号整数的范围 −231, 231 − 1 ,就返回 0。假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入:x = 123

输出:321

示例 2:

输入:x = -123

输出:-321

示例 3:

输入:x = 120

输出:21

示例 4:

输入:x = 0

输出:0

提示:

  • -231 <= x <= 231 - 1

解答一

将 x 转成字符串,再反转字符串

ini 复制代码
function reverse(x: number): number {
    const s = (x + '').split('')
    let low = s[0] === '-' ? 1 : 0
    let high = s.length - 1

    while(low < high) {
        const temp = s[low]
        s[low] = s[high]
        s[high] = temp
        low ++
        high --
    }
    const num = Number(s.join(''))
    if (num > Math.pow(2,31) || num < Math.pow(-2,31)-1) {
        return 0
    }
    return num
};

解答二

关键公式 result = result * 10 + x % 10,x = x / 10

sql 复制代码
function reverse(x: number): number {
    let result = 0
    while(x !== 0) {
        result = result * 10 + x % 10
        x = x > 0 ? Math.floor(x / 10) : Math.ceil(x / 10)
    }

    if (result > Math.pow(2,31) || result < Math.pow(-2,31)-1) {
        return 0
    }

    return result
};
相关推荐
一起学安全技术3 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
️公子3 小时前
可插拔 13 款实时棋牌对战平台实践:房间容器、Plugin SDK 与幂等账本
websocket·typescript·游戏开发·monorepo·插件架构·棋牌平台·实时对战
FungLeo4 小时前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome
Delightrs4 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信150413057594 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
FungLeo5 小时前
成为全栈·Vue管理后台篇·<scriptsetup>:把页面拆成可读、可测的 Vue 组件
前端·javascript·vue.js·typescript·前端组件化·composition api·vue sfc
GoAI16 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi16 小时前
力扣54.螺旋矩阵
算法·leetcode·矩阵
choumou_M19 小时前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法