LeetCode 7. Reverse Integer (JS)

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

周二太忙了...没时间刷题...趁着周三中午有时间赶忙刷一波

先Po代码:

var reverse = function(x) {
    var sum = 0,
        flag = 0;
    const MAXINIT = Math.abs((1<<31)-1);
    if (x < 0) {
        x = -x;
        flag = 1;
    }
    while (x > 0) {
	    sum = sum * 10 + x % 10;
	    x = Math.floor(x / 10);
    }
    if (sum > MAXINIT) {
        sum = 0;
    }
    return flag ? -sum : sum;
};

题解:

一开始真真没考虑到32位int溢出的问题...

然后WA了如下错误:

Input:
1534236469
Output:
9646324351
Expected:
0

即,如果溢出,那么返回0

由于我这里使用的是绝对值,所以不需要考虑下溢,int32位最大值,即2的31次方-1,(因为如果对任何数字做位运算,JS都会将其转为32位有符号整形,而1<<31,把1移到了符号位,使其为-2147483648)

这个问题自己研究了一下,发现了几点

(1<<31)-1; //首先,进行位运算要带括号,不然优先计算31-1=30,再1<<30;
1<<31;//-2147483648,因为转为了有符号整形,所以1<<31位溢出,把1移到了符号位。

以上,这个题还是比较easy的......(自己本来也就刷的是easy题,囧)

收获就是JS位运算的相关知识了......

原文地址:https://www.cnblogs.com/kiznaiver1998/p/8616268.html