码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 每日一题 7.整数反转

时间:2020-04-20 13:36:32      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:http   思路   min   大于   col   width   inf   return   每日   

技术图片

1.整除取余

思路:

对原整数循环对10取余和整除,然后进行拼接。这里需要注意的时,在整除时要考虑如果原整数大于最大值或者小于最小值的情况。

例如:

原整数 x = 123 翻转后整数 new_x = 0  余数为 p  

① x != 0  则  p = x%10 = 123%10 = 3,x = x // 10 = 123//10 = 12,new_x=new_x*10+p = 0*10 + 3 = 3

② x != 0  则  p = x%10 = 12%10 = 2,x = x // 10 = 12 // 10 = 1,new_x=new_x*10+p = 3*10 + 2 = 32

③ x != 0  则  p = x%10 = 1%10 = 1,x = x // 10 = 1 // 10 = 0,new_x=new_x*10+p = 32*10 + 1 = 321

④ x == 0 则 返回new_x

代码:

class Solution:
    def reverse(self, x: int) -> int:
        result = 0
        maxsize = 2**31-1
        minsize = -2**31
        while x != 0:
            pop = x % 10
            x //= 10
            if x > maxsize//10 or (x == maxsize//10 and pop > 7):
                return 0
            if x < minsize//10 or (x == minsize//10 and pop < -8):
                return 0
            result = result * 10 + pop
        return result

2.整数转字符串再转整数

思路:

先将整数变成字符串,然后对字符串取反,再把字符串转为整数。这里在对字符串操作时,要考虑负数情况,同时对结果进行最大最小判断。

代码:

class Solution:
    def reverse(self, x: int) -> int:
        str_num = str(x)[::-1]
        if str_num.endswith(-):
            str_num = - + str_num[:-1]
        if int(str_num) < -2**31:return 0
        if int(str_num) > 2**31 - 1: return 0
        return int(str_num)

 

leetcode 每日一题 7.整数反转

标签:http   思路   min   大于   col   width   inf   return   每日   

原文地址:https://www.cnblogs.com/nilhxzcode/p/12736966.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!