Day 4: Buckle the seventh question, integer inversion

Address: leetcode-cn.com/problems/re…

I’m going to go straight to arrays, because arrays have a method called inversion. Without further ado, go straight to the code:

var reverse = function(x) {
let a = Math.abs(x).toString().split(“”).reverse().join(“”); // Convert to array inversion and then to string output.
if(a>2**31-1)
{return 0; }
if(x>=0)
{return a; }
else{
return -a;
}
};  

Execution time: 104 ms, beating 59.94% of users in all JavaScript commits
Memory consumption: 38.9 MB, beating 22.01% of all JavaScript commits

At the same time found a big guy code:

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;

};

His mind I can understand, it is more than by taking the digital turned around, there’s a little knowledge, he is | 0, is the integer, | 0 = 10, 10.5 but | 0-10.5-10, with the Math. The floor is different, so the method reduces the running load.

In fact, the preceding can be understood, but I still can not understand the last code, his last code means that the first round result, and then the absolute comparison with result, === equals, will return true only when the value and type are all equal, if true return result, otherwise return 0;

He is to use this method to judge whether the overflow, but I still can’t understand why can determine overflow, the (result) | 0 = = = the result is not very good, I am a “do-it-yourself” course.

There it is: the bottom of the article