You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode反转整数解法为何出现无限循环?

LeetCode反转整数函数的无限循环问题解析

你写的反转整数函数在处理负数时陷入无限循环,核心原因是Math.floor()对负数除法的处理逻辑导致x永远无法趋近于0。

你的代码

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(b) {
    let x = b;
    let result = 0;
    while(x !== 0) {
        console.log(`tomato: ${x}`)
        let digit = x % 10;
        console.log({digit});
        result = result * 10 + digit;
        console.log({result});
        x = Math.floor(x / 10)
        console.log(`potato ${x}`);
    }
    return result;
};

关键问题分析

当传入负数(比如-123)时,Math.floor(x / 10)的行为和正数完全不同:

  • 正数场景:123 / 10 = 12.3,Math.floor(12.3)得到12,x会逐步递减到0,循环正常终止。
  • 负数场景:-123 / 10 = -12.3,Math.floor(-12.3)会向下取整到**-13**(而非预期的-12),后续每一步计算都会让x陷入死循环:
    • x = -13 → Math.floor(-13/10) = -2
    • x = -2 → Math.floor(-2/10) = -1
    • x = -1 → Math.floor(-1/10) = -1
      此时x永远等于-1,满足x !== 0的循环条件,导致无限循环。

你日志里出现potato 0后又tomato: -123,应该是连续调用了reverse(123)和reverse(-123),前者正常结束,后者触发了无限循环。

修复方案

把Math.floor(x / 10)换成parseInt(x / 10),或者用ES6+支持的Math.trunc(x / 10),这两个方法处理负数除法时会直接截断小数部分,得到预期的整数结果:

  • -123 / 10 = -12.3 → parseInt(-12.3)或Math.trunc(-12.3)都得到-12
  • 后续x会逐步递减到0,循环正常终止。

另外补充LeetCode题目要求的溢出判断,当反转结果超出32位有符号整数范围时需返回0,修复后的代码示例:

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(b) {
    let x = b;
    let result = 0;
    while(x !== 0) {
        let digit = x % 10;
        result = result * 10 + digit;
        // 替换为Math.trunc或parseInt
        x = Math.trunc(x / 10);
    }
    // 32位有符号整数范围判断
    const min = Math.pow(-2, 31);
    const max = Math.pow(2, 31) - 1;
    if (result < min || result > max) {
        return 0;
    }
    return result;
};

内容的提问来源于stack exchange,提问作者StudioWorks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:20:15