JS Likou classic 100 questions - integer inversion

Given a 32-bit signed integer x, return the result of inverting the numeric portion of x.

Returns 0 if the inverted integer exceeds the range [−231, 231 − 1] of a 32-bit signed integer.
Assume the environment does not allow storing 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

hint:

    -231 <= x <= 231 - 1

Problem-solving ideas: Process according to the Number type, get the last digit of the original number each time, and gradually change it to a high digit. The last digit of the original number is removed every cycle, but manual rounding is required in js. Here, |0 is added after the number, that is, it is rounded toward 0, negative numbers are rounded toward zero, and positive integers are also rounded toward zero. all.

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    let result = 0;

    while(x !== 0) {
        result = result * 10 + x % 10;  // 累加
        x = x / 10 |0;  // js取整操作,在后面加|0
        console.log(x)
    }
    return result < -Math.pow(2,31)-1 || result > Math.pow(2,31) ? 0 : result;
};

If you don't do the rounding operation, you will always take decimals and keep taking decimals.

 

 

Guess you like

Origin blog.csdn.net/qq_36384657/article/details/128227759