其他分享
首页 > 其他分享> > Leetcode(7)整数反转

Leetcode(7)整数反转

作者:互联网

Leetcode(6)Z字形变换

[题目表述]:

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

第一次:转字符串处理

执行用时:40 ms; 内存消耗:11.6MB 效果:很好

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x>=0:
            r=str(x)
            r=r[::-1]
            n=int(r)
        else:
            r=str(-x)
            r=r[::-1]
            n=-(int(r))
        if x>(2**31-1) or x<(-2)**31:
            return 0
        return n

学习

第二种方法:转列表处理

执行用时:40 ms; 内存消耗:11.6MB 效果:很好

class Solution:
    def reverse(self, x: int) -> int:
        s = ''
        s = s.join(i for i in str(x))
        if s[0] == '-':
            s = s[1:] + '-'
        return int(s[::-1]) if -2**31<int(s[::-1])<2**31-1 else 0

学习

第三种方法:移位运算

执行用时:56 ms; 内存消耗:11.6MB 效果:还行

class Solution:
    def reverse(self, x: int) -> int:
        a = str(x)
        if(x >= 0):
            m = int(a[::-1])
            return m if m <= ((1<<31)-1) else 0
        else:
            n = -int(a[:0:-1])
            return n if n >= (-(1<<31)) else 0

学习

标签:reverse,int,反转,11.6,Solution,整数,class,str,Leetcode
来源: https://www.cnblogs.com/ymjun/p/11681723.html