美文网首页
2、整数反转 leetcode7

2、整数反转 leetcode7

作者: 九答 | 来源:发表于2020-04-01 11:55 被阅读0次

    题目描述

    description.png

    思路:这题用python首先想到的就是转化成数组,用[::-1]来做。但是为了好好学习,还是少用点内置算法。x右移/10,num左移*10,用while

    class Solution:
        def reverse(self, x: int) -> int:
            y = abs(x)
            nums = 0
            while(y!=0):
                num = y%10
                nums = nums*10 + num
                y = y//10
                
            if nums>- pow(2,31) and nums < pow(2,31)-1:
                return nums if x > 0 else -nums
            else:
                return 0
    

    另外用python反转的方法:

    class Solution:
        def reverse(self, x: int) -> int:
            y,num = abs(x),0
            num = int(str(y)[::-1])
            if num  > -pow(2,31) and num < pow(2,31)-1:  
                return num if x>0 else -num
            else:
                return 0
    

    相关文章

      网友评论

          本文标题:2、整数反转 leetcode7

          本文链接:https://www.haomeiwen.com/subject/emyouhtx.html