Integer Reverse (Python)

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 [−2 ** 31, 2 ** 31 − 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

Idea 1: Convert the signed integer to a string, remove the sign bit, reverse the string, and then convert it to an integer (pay attention to the restoration of the original symbol), and finally judge whether it overflows.

def reverse(x):
    if x == 0:
        return 0
    s = str(x)
    s = s.replace("-","")  # abs() 也可以用
    re = s[::-1]  # 反转
    re = [-1,1][x > 0] * int(re)  # 正负 if - else 判断
    if not -2**31 <= re <= 2**31-1:
        return 0
    return re

if __name__ == "__main__":
    x = 120
    print(reverse(x))

Code simplification: Python3.1+, comes with a bit_length() method that allows you to query the number of digits or length of a binary.

def reverse(self, x: int) -> int:
	# re = [-1, 1][x > 0] * int(str((x))[::-1].replace('-',''))
	re = [-1,1][x > 0] * int(str(abs(x))[::-1])
    return re if re.bit_length() < 32 else 0

If - else judgment usage see: https://blog.csdn.net/qq_43325582/article/details/122544661

Idea 2: Mathematical method, take out the last number, then add it to the returned number, and then overflow judgment. The topic requires that 64-bit integers are not allowed, that is, the numbers in the operation must be within the range of 32-bit signed integers.

  • num = x % 10
  • x /= 10
  • re = re*10 + num (initial: re = 0)
class Solution:
    def reverse(self, x: int) -> int:
        INT_MIN, INT_MAX = -2**31, 2**31 - 1
        rev = 0
        while x != 0:
            # INT_MIN 也是一个负数,不能写成 rev < INT_MIN // 10
            if rev < INT_MIN // 10 + 1 or rev > INT_MAX // 10:
                return 0
            digit = x % 10
            # Python3 的取模运算在 x 为负数时也会返回 [0, 9) 以内的结果,需要进行特殊判断
            if x < 0 and digit > 0:
                digit -= 10

            # Python3 的整数除法在 x 为负数时会向下(更小的负数)取整,因此直接 x //= 10
            x = (x - digit) // 10
            rev = rev * 10 + digit
        return rev

Guess you like

Origin blog.csdn.net/qq_43325582/article/details/122713477