007 reverse

题目描述

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321
 示例 2:

输入: -123
输出: -321
示例 3:

输入: 120
输出: 21
注意:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

代码

字符串法

思路:简单粗暴的用字符串反转解决。

def reverse(x):
    """
    :type x: int
    :rtype: int
    """
    x=list(str(x))
    if x[0] == '-':
        x = x[1:]
        y = list(reversed(x))
        y = ''.join(y)
        y = '-' + y
        y = int(y)
    else:
        y = list(reversed(x))
        y = ''.join(y)
        y = int(y)
    if y > pow(2,31)-1 or y < -pow(2,31):
        return 0
    else:
        return y

数字计算法

思路:先将数字转换成无符号的数字;取模,累加变量*10+取模数字,原数字除10;重复上述步骤直到原数字除成了0。

def reverse(self, x):
    """
    :type x: int
    :rtype: int
    """
    if x < 0 :
        y = -x
    else:
        y = x
    count = 0
    while True:
        b = y % 10
        if y != 0:
            count = count * 10 + b
            y = y // 10
        else:
            if x < 0 and (-count) >= -pow(2,31):
                return -count
            elif x > 0 and count <= pow(2,31)-1 :
                return count
            else:
                return 0

猜你喜欢

转载自blog.csdn.net/double___you/article/details/80378709
007