Preface explains

Algorithm learning, daily brush record.

Subject to connect

Integer inversion

The subject content

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 [−2^31, 2^31 − 1], 0 is returned.

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

Example 1:

Enter x = 123

Output: 321

Example 2:

Enter x = -123

Output: – 321

Example 3:

Enter: x = 120

Output: 21

Example 4:

Enter: x = 0

Output: 0

Tip:

-2^31 <= x <= 2^31 – 1

The analysis process

Sum is defined as the inverted integer, starting at 0, and multiplying the remainder by 10 each time gives the inverted integer.

Let’s say 123.

So the first time I get 3, 0 times 10 plus 3 is 3.

The second time I get 2, 3 times 10 plus 2 is 32.

The third time I get 1, 32 times 10 plus 1 is 321.

It’s exactly 321 flipped over from 123.

To solve the code

So here’s the solution code:

class Solution { public int reverse(int x) { int n = x; If (x < 0) {// If (x < 0) {// If (x < 0); } int sum = 0; While (x > 0) {int m = x % 10; while (x > 0) {int m = x % 10; Int temp = sum; // Multiply by 10 plus the remainder, and every time you multiply by 10, you get 10 times more, and you get minus the last digit, but here you add the last digit, m, and because you keep dividing by 10, you get the opposite number, so this is exactly the reversed integer sum = sum * 10 + m; if (sum / 10 ! = temp) {return 0; } // x divided by 10 minus the rightmost bit x = x / 10; } if (n < 0) {sum = sum * -1; } return sum; }}Copy the code

Submit the results

It took 1ms to execute, beating 100.00% of users in time, 35.4MB of memory consumption, and 75.77% of users in space.

The original link

Integer inversion