Nuggets team number online, help you Offer impromptu! Click on theCheck the details

1. Title Description

You are given a 32-bit signed integer x that returns the result of reversing the numeric portion of x. Assume that the environment does not allow storage of 64-bit integers (signed or unsigned). Eg1: input: x = 123 Output: 321 EG2: input: x = -123 Output: -321 EG3: input: x = 120 Output: 21 EG4: input: x = 0 Output: 0Copy the code

Second, train of thought analysis

<0 and >= 0 2. <0 and >= 0 2. The result of the inversion is in the range of −2^31, 2^31 − 1Copy the code

Three, the solution code

  1. Idea 1: Reverse the string
  / * * *@param {number} x
    * @return {number}* /
    
var reverse = function(x) {
    let result = x.toString().split(' ').reverse().join(' ')
    if (x < 0) {
        return -result < -Math.pow(2.31)?0 : -result
    }
    return +result > (Math.pow(2.31) - 1)?0 : +result
};

Copy the code
  1. Idea 2: mod method
/ * * *@param {number} x
 * @return {number}* /
var reverse = function(x) {
    let abs = Math.abs(x) // Take the absolute value
    let now = 0
    while(abs > 0) {
        now = now * 10 + abs % 10 // mod inversion
        abs = Math.floor(abs / 10)}if (x < 0) {
        return now <= Math.pow(2.31)? -now :0
    } else {
        return now > (Math.pow(2.31) - 1)?0 : now
    }
};

Copy the code

Four,

  • Look at manipulation of numbers, such as math.abs (), math.pow (), and so on.
  • It would be nice to be more careful in this case.