Given a 32-bit signed integer, reverse digits of an integer.

Note:
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

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

Constraints:
-2^{31} <= x <= 2^{31} - 1

Solution in python:

class Solution:
    def reverse(self, x: int) -> int:
        if x > 0:
            sign = 1
        else:
            sign = -1
            x = -x
        value = 0
        while x > 0:
            reminder = x % 10
            value = 10 * value + reminder
            x //= 10
        if -2**31 <= sign*value <=2**31:
            return sign*value
        else: return 0
最后修改日期: 2020年10月14日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。