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) = -2x = -2→Math.floor(-2/10) = -1x = -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
相关产品推荐
相关产品推荐

