Interview icon indicating copy to clipboard operation
Interview copied to clipboard

第338题(2020-10-30):leetcode7:整数反转(腾讯)

Open qappleh opened this issue 5 years ago • 1 comments

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

qappleh avatar Oct 30 '20 02:10 qappleh

极简数学解法,运用JavaScript位运算

解题思路

  • result * 10 + x % 10 取出末位 x % 10(负数结果还是负数,无需关心正负),拼接到 result 中。
  • x / 10 去除末位,| 0 强制转换为32位有符号整数。
  • 通过 | 0 取整,无论正负,只移除小数点部分(正数向下取整,负数向上取整)。
  • result | 0 超过32位的整数转换结果不等于自身,可用作溢出判断。

运算过程:

x	result
123	0
12	3
1	32
0	321

代码

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    let result = 0;
    while(x !== 0) {
        result = result * 10 + x % 10;
        x = (x / 10) | 0;
    }
    return (result | 0) === result ? result : 0;
};

qappleh avatar Nov 03 '20 03:11 qappleh