您的位置:首页 > 其它

leetcode 7. Reverse Integer

2018-03-15 13:07 519 查看
本题要考虑边界条件32bit有符号int最大值为2^31-1,最小为-2^31,整数反转思想如下代码
Given a 32-bit signed integer, reverse digits of an integer.Example 1:Input: 123
Output: 321
Example 2:Input: -123
Output: -321
Example 3: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.

Solution
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        y = 0
        flag = True
        if x < 0:
            flag = False
            x = abs(x)
        max_v = 2**31 -1
        max_neg_v = 2**31
        while x != 0:
            y = y * 10 + x % 10
            x = int(x / 10)
            if flag and y > max_v:
                return 0
            elif not flag and y > max_neg_v:
                return 0
                
        if flag:
            return y
        else:
            return -y
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 整数反转