[Power button - small daily practice] 7. integer reversal (python)

7. integer reversal

Title Description

Given a 32位signed integer, you will need this number on every integer be 反转.

Examples

Example 1:
Input: 123
Output: 321

Example 2:
Input: -123
Output: -321

Example 3:
Input: 120
Output: 21

note:Suppose we have an environment can only store a 32-bit signed integer, then the value range [-2 ^ 31, 2 ^ 31 - 1] Please According to this hypothesis, if integer overflow after reverse it returns 0.

Code

class Solution:
    def reverse(self, x: int) -> int:
        x = str(x)
        flag = 1
        if x[0] == '-':
            flag=0
            x=x[1:]
        y = list(x)
        y.reverse()
        y = int(''.join(y))
        if y > 2**31-1 or y < -2**31-1:
            y = 0
        if flag == 0:
            return -y
        else:
            return y
Published 44 original articles · won praise 5 · Views 4467

Guess you like

Origin blog.csdn.net/ljb0077/article/details/104725231