前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q7 Reverse Integer

Q7 Reverse Integer

作者头像
echobingo
发布2018-04-25 16:30:44
5230
发布2018-04-25 16:30:44
举报

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

Example 1:
代码语言:javascript
复制
Input: 123
Output:  321
Example 2:
代码语言:javascript
复制
Input: -123
Output: -321
Example 3:
代码语言:javascript
复制
Input: 120
Output: 21

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.

解题思路:

将整数转化为字符串,处理完后转化为整数

注意点:

原数字和转化后的数字都不能溢出

Python实现:
代码语言:javascript
复制
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        min = -2**31
        max = 2**31 - 1
        if  x < min or x > max or x == 0:  # 0 不用反转
            return 0
        if x > 0:
            rev = int(str(x)[::-1])  # [::-1]字符串反转
        else:
            rev = -int(str(x)[1:][::-1])
        if rev < min or rev > max:  # 反转后的数字溢出
            return 0
        return rev

a = 1023456789
b = Solution()
print(b.reverse(a))  # 转化后的数字溢出,返回0
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example 1:
  • Example 2:
  • Example 3:
  • 解题思路:
  • 注意点:
  • Python实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档