leetcode--Reverse Integer

来源:互联网 发布:ipaf看书软件 编辑:程序博客网 时间:2024/06/05 11:50

题目:难度(Easy)

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?
    Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
    If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
    Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Tags:Math
Similar Problems:(E) String to Integer (atoi)

分析:将输入x不断的除以10,所产生的余数刚好是x各个数位的倒置,例如123不断除以10,先后产生的余数分别是3、2、1。利用这个特点,那么结果值result即为result*10加上所产生的余数,并如此循环下去。需要注意的是溢出的问题,设32为整数的最大值为MAX,那么在result*10+余数之后可能会得到一个>MAX的数从而导致溢出,所以需要在这之前判断一下result是否已经大于了(MAX-余数)/10,如果没有大于,那么得到的新的result也不会大于MAX。按题意,如果溢出就要返回0。

代码实现:

class Solution(object):    def reverse(self, x):        MAXINT = pow(2, 31) - 1        #flag = 1表示x是正数,flag = -1 表示x是负数        flag = 1        if x < 0:            flag = -1        x = abs(x)        result = 0        while x != 0:            #x%10得到的余数刚好是逆向产生的,即先产生个位、再十位。。。            #result每次都乘以10+i,可能会导致溢出,所以需要在乘之前,做以下会不会溢出的判断,会则返回0            if result > (MAXINT-x%10)/10:                return 0            else:                result = result * 10 + x%10            x/=10        return result * flag
也可以使用python的字符串比较来实现。MAXINTSTRING = pow(2, 31) - 1 = 2147483647 是一个十位数,而输入的最大位数也不会操作10位数,将x的绝对值转换为字符串,利用分片操作[::-1]将输入x进行倒置以后,如果串x的长度等于10,则需要判断是否溢出,这里直接与MAXSTRING进行字符串比较即可,如果串x的长度<10,则一定不会溢出,直接将已经倒置的x返回即可(当然还要注意正负问题)。

代码实现:

class Solution(object):    def reverse(self, x):        """        :type x: int        :rtype: int        """        #MAXINTSTRING = 2147483647 是一个十位数        #输入x是一个int,所以int的最大位数也不可能超过10位        MAXINTSTRING = str(pow(2, 31) - 1)        flag = 1        if x < 0:            flag = -1        x = str(abs(x))[::-1]        if len(x) == 10 and x > MAXINTSTRING:            #可能一处            return 0        else:            return int(x) * flag



0 0
原创粉丝点击