LeetCode-7 Reverse Integer

Description

Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which 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

Example 1:
Input: 123
Output: 321

Example 2:
Input: -123
Output: -321

Example 3:
Input: 120
Output: 21

Submissions

我的解题思路是将整型数字x转成字符串取反,再转成整型.首先判断x是否小于0,如果小于0则取除去符号的部分转成字符串取反,转成整型后再加上符号.需要注意的是最后要判断取反后是否溢出,范围在 [−231, 231 − 1],若溢出则结果返回0.

实现代码如下:

class Solution:
    def reverse(self, x: int) -> int:
        if x < 0:
            rev = -1*int((str(-x))[::-1])
        else:
            rev = int((str(x))[::-1])
        if rev < -2**31 or rev > 2**31-1:
            return 0
        return rev

Runtime: 28 ms
Memory Usage: 12.7 MB

LeetCode-7 Reverse IntegerLeetCode-7 Reverse Integer 温暖℡ 发布了8 篇原创文章 · 获赞 0 · 访问量 121 私信 关注
上一篇:Leetcode - 7. 整数反转


下一篇:Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0