[LeetCode][Python]7. Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

解题思路:

  1. python里面int最大数值0x7FFFFFFF,在考虑溢出的时候需要和这个值进行比较。

  2. 取模运算可以得到数字的最后一位,/运算会得到移走最后一个数字之外的数字,以此循环

    代码如下:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        res = 0
        flag = -1 if x<0 else 1
        x = x * flag

        while(x):
            res = res*10 + x%10
            x = x/10
        if res > 0x7FFFFFFF:
            return 0
        return res*flag

if __name__ == "__main__":
    sol = Solution()
    print sol.reverse(123)
    print sol.reverse(1000)
    print sol.reverse(10001)
    print sol.reverse(-123)
    print sol.reverse(1000000003)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,552评论 5 6
  • 这两天通过学习,我决定改变和女儿的恶劣关系。从上初中起女儿爱上打扮,每天都要化妆,为这事冲突不断,我觉的这个年龄应...
    可乐开心阅读 619评论 2 4
  • 静静地坐在教室里,两眼环视着教室,偌大的教室只有4个人而已,心中不免多了一丝担忧与迷茫,其他同学去画室上美术课了,...
    xiao嫣阅读 422评论 0 1
  • 离开了,我才开始重视自己。我会努力变得更好的。你有一只粉色猪猪。好在我还有一只蓝色的。 中秋佳节,忍不住跑回家吃中...
    猪悟能阅读 208评论 0 0