算法(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
};
相关推荐
Savior`L1 天前
二分算法及常见用法
数据结构·c++·算法
mmz12071 天前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻1 天前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习1 天前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~1 天前
排序---常用排序算法汇总
数据结构·算法·排序算法
AndrewHZ1 天前
【遥感图像入门】DEM数据处理核心算法与Python实操指南
图像处理·python·算法·dem·高程数据·遥感图像·差值算法
CoderYanger1 天前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习1 天前
面试150——第二周
数据结构·算法·leetcode
liu****1 天前
3.链表讲解
c语言·开发语言·数据结构·算法·链表