Leetcode(7)整数反转

时间:2019-10-15
本文章向大家介绍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

学习

  • 列表处理不用考虑是否是纯数字

  • if表达式不太熟练

  • ['' for x in range(numRows)] ''.join(L)

第三种方法:移位运算

执行用时: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

学习

  • 用移位代替**

原文地址:https://www.cnblogs.com/ymjun/p/11681723.html