Integer inversion【JavaScript】

Given a 32-bit signed integer, you need to invert the digits on each of the integers.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:

Assuming that our environment can only store 32-bit signed integers, the value range is [−231, 231 − 1]. According to this assumption, if the integer overflows after the inversion, it returns 0.

Specific solution (1):
var reverse = function(x) { var num; num = parseInt(x.toString().split('').reverse().join('')); if(num>Math. pow(2,31)-1) return 0; else{ if(x>=0) return num; else(x<0) return -num; } }; This method uses JavaScript string conversion, not Mathematical thinking, but the string conversion efficiency is low and it depends on the API, and the time and memory consumption are greater than the following method; Method 2: var reverse = function(x) { let result = 0; let value = Math.abs( x); while (value !== 0) { result = result * 10 + value% 10; value = Math.floor(value / 10); } result = x> 0? result:-result;





















return (result> Math.pow(2,31)-1 || result <-Math.pow(2,31)? 0: result);
};
I think this method is more difficult to understand than method 1, I When I did it, I also considered the first method, so please adopt this method yourself.

In addition, see a more concise approach:
var reverse = function(x) { let fh = “”, re; if(x<0){ fh = “-”; x = 0-x; } re = ( x+"").split("").reverse().join(""); if(re.length>10 || re.length === 10 && re> (x<0?"2147483648":" 2147483647”)){ return 0; }else{ return fh + re; } };











Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/104844782