This is the 25th day of my participation in the Gwen Challenge.More article challenges

For a better tomorrow, keep brushing LeetCode!

The title

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 1:

Input: x = 123 Output: 321Copy the code

Example 2:

Input: x = -123 Output: -321Copy the code

Example 3:

Input: x = 120 Output: 21Copy the code

Example 4:

Input: x = 0 Output: 0Copy the code

Tip:

-231 <= x <= 231 - 1
Copy the code

Solution number one – math

Their thinking

Get the last bit of XXX each time and append to the last bit of another digit revrevrev:

Rev = rev * 10 + last = x % 10 x = x / 10Copy the code

code

func reverse(x int) (rev int) {
    forx ! =0 {
        if rev < math.MinInt32/10 || rev > math.MaxInt32/10 {
            return 0
        }
        digit := x % 10
        x /= 10
        rev = rev*10 + digit
    }
    return
}
Copy the code

The execution result

Execution time: 0 ms, beat 100.00% user memory consumption in all Go commits: 2.1 MB, beat 63.53% of users in all Go commitsCopy the code

Complexity analysis

  • Time complexity: O(log∣x∣)O(log∣x∣). The number of flips is the number of XXX decimal digits.
  • Space complexity: O(1)O(1)O(1)

Topic link

7. Integer inversion

Similar to the topic

  • String conversion to integer (atoi)
  • Reverse binary