美文网首页
LeetCode - Reverse Integer

LeetCode - Reverse Integer

作者: Jansid | 来源:发表于2017-11-26 21:31 被阅读313次

Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

给一个32位的有符号整数,翻转这个数字。
注意:
假设我们在一个只能处理32位有符号整数范围的环境中。为了解决这个问题,假如翻转后的数字溢出则函数返回0。

Example:

Input: 123
Output:  321

Input: -123
Output: -321

Input: 120
Output: 21

分析: 32位的整数范围为: -2147483648 ~ 2147483648,因此,正常返回结果的数字需要在-231 ~ 231范围内。翻转可以使用字符串来实现。

def reverse(x):
    str_x = str(abs(x))
    num = int(str_x[::-1])
    if num > 2147483648: return 0
    if x < 0: return -num
    return num

相关文章

网友评论

      本文标题:LeetCode - Reverse Integer

      本文链接:https://www.haomeiwen.com/subject/rumkbxtx.html