力扣整数反转

力扣整数反转

要求

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

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

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

输入: 120
输出: 21
注意:

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

思路1

思路:1.将整数转为字符串然后去掉符号,
2.再将字符串反转 左边有零去掉 右边的符号去掉,
3.最后左边再加上符号 ,再转为整数。

代码片

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        
        if x==0:
            return 0
        str_x=str(x)
        x=''
        if str_x[0]=='-':
            x+='-'
        x+=str_x[len(str_x)-1::-1].lstrip("0").rstrip("-")
        x=int(x)
        if -2**31<x<2**31-1:
            return x
        return 0

思路2

思路:1.将x 先转为正数 。
2.然后循环遍历这个数,取余反转
3.最后再利用x 给res加符号
代码片

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        n = x if x > 0 else -x
        res = 0
        while n:
            res = res * 10 + n % 10
            n = n // 10 
        if res > 0x7fffffff:
            return 0
        return res if x > 0 else -res

猜你喜欢

转载自blog.csdn.net/weixin_41781408/article/details/86549128