Python3_Leetcode #7 整数反转题解

时间:2021-07-08 10:19:37   收藏:0   阅读:32

思路:

  采用数学方法,诸位取出最后一位数字,然后通过X10,把最后的数乘到最前。python应注意先把数字转换成正数处理,因为负数的求商和取余会是地板除,即向低取整数,例如  商为-11/10 = -1.1-->-2,  余数=被除数-除数*商  -11-10*-2 = 9.  所以直接取余会是错误的数。

 

所以:

1.将数字x转换为正数,如果是负数则给个标志

2.x 不断与10取余,得到最后的数,并通过x10变成高位的数

3.如果是负数乘上 -1 , 判断数字是否在范围,如果是则返回,不是则返回0

 

技术分享图片

 

 

 

python 3:

class Solution:
    def reverse(self, x: int) -> int:
        sign = 1
        ret = 0
        if x < 0:
            x = abs(x)
            sign = -1
        while x > 0:
            # x, tmp = divmod(x, 10)
            tmp = x % 10
            ret = ret * 10 + tmp
            x =int(x/ 10)    #如果不用divmod函数,这里x需记得转成int,因为不加的话会是个小数
        ret *= sign
        if -2 ** 31 <= ret <= 2 ** 31 - 1:
            return ret
        else:
            return 0
 
------------------------------------------------------------------------------------------------------------------
class Solution:
    def reverse(self, x: int) -> int:
        sign = 1
        ret = 0
        if x < 0:
            x = abs(x)
            sign = -1
        while x > 0:
            x, tmp = divmod(x, 10)   # divmod函数是Python的内置函数,它可以把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)
        
            ret = ret * 10 + tmp
        
        ret *= sign
        if -2 ** 31 <= ret <= 2 ** 31 - 1:
            return ret
        else:
            return 0

原文:https://www.cnblogs.com/manshuoli/p/14984219.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!