First, understand the topic

7. Integer inversion

You are given a 32-bit signed integer x that returns the result of reversing the numeric portion of x.

If the inverted integer exceeds the range of 32-bit signed integers [−231, 231 − 1], 0 is returned.

Assume that the environment does not allow storage of 64-bit integers (signed or unsigned).

Example:

Input: x = 123 Output: 321Copy the code

2. How to solve the problem

In order to solve the problem, we should write down the following ideas:

  • On the firstxValue unsigned;
  • Define a value to hold the inverted number;
  • Reverse each number progressively.

Three, code implementation

Based on the above solution, we will use JS to implement this problem. The specific implementation code is as follows:

var reverse = function(x) {
    // 1
    let ord = Math.abs(x);
    // 2. Define a value to store the inverted number
    let now = 0;
    // 3. Judge condition: order must >0
    while(ord > 0) {// 3.1 Reverse one by one
        now = now * 10 + ord % 10;
        // 3.2
        ord = Math.floor(ord / 10);
    }
    // 4. Return the result
    if(x < 0) {return now <= Math.pow(2.31)? -now :0;
    }else{
        return now < Math.pow(2.31)? now :0; }};console.log(reverse(120333)); / / 333021
Copy the code

The above is about taking the inverse number of the problem solution, DO not know whether it is helpful to small friends?

We’ll see you next time at 👋👋👋