This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging
The title
Give you a 32-bit signed integer x and return the result of reversing the numeric portion of x.
If the reversed integer exceeds the range of 32 bit signed integers [−231, 231 − 1], 0 is returned.
Assume that the environment does not allow the storage of 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
Example 4:
Input: x = 0 Output: 0
Tip:
-231 <= x <= 231 - 1
Their thinking
Idea 1
To reverse a number, the first thing that comes to mind is to take mod, but you might run into a situation where the number exceeds the maximum limit or the minimum limit.
So we can reverse it and detect it at the same time, and if we do that, if we have a problem, it will stop immediately.
code
var reverse = function(x) {
let res = 0;
while(x){
res = res * 10 + x % 10;
if(res > Math.pow(2.31) - 1 || res < Math.pow(-2.31)) return 0;
x = ~~(x / 10);
}
return res;
};
Copy the code
Idea 2
Convert x from Number to String, split the String into Array using String method split, reverse the Array method reverse, and join the Array method convert the Array to String. Finally, we use parseInt to change the String back to Number.
Because of the split character array, the last step of processing the String loses its ending minus sign when x is less than 0, so the result is a negative sign when x is less than 0.
/ * * *@param {number} x
* @return {number}* /
var reverse = function (x) {
let y = parseInt(x.toString().split("").reverse().join(""));
if (x < 0)
y = - y;
return y > 2147483647 || y < -2147483648 ? 0 : y;
};
Copy the code
The last
I dreamed of going all over the world with a sword
Take a look at the prosperity of the world
Young hearts are always a little frivolous
Just a man after all
No regrets I go my way
“Front brush” No.7