Leetcode 7 Reverse Integer

来源:互联网 发布:php 判断数据类型 编辑:程序博客网 时间:2024/06/16 07:13

7.Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

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.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

题目不难,将一个数字反转即可,不过需要注意32位整数的取值范围:

class Solution(object):    def reverse(self, x):        """        :type x: int        :rtype: int        """        if x >= 0:            result = int(str(x)[::-1])            return 0 if result > 2 ** 31 - 1 else result        else:            result = int(str(abs(x))[::-1])            return 0 if result > 2 ** 31 else -result
  • 我是将数字转化成字符串后进行反转操作,由于数字有可能是负的,因此分了两种情况进行处理
  • 如果数字是负的,取绝对值反转,然后再转成负的

当然,上述代码只是一种实现的方式,还有很多实现的方法也很有趣,下面这段代码是在leetcode的submission中看到的

class Solution(object):    def reverse(self, x):        """        :type x: int        :rtype: int        """        s=(x>0)-(x<0)        r=int(str(abs(x))[::-1])        return s*r*(r<2**31)
  • 通过s = (x > 0) - (x < 0)来计算x的正负,并在返回结果时决定返回正数还是负数
  • 如果数字超出范围了,则 r<2**31为False,与s和r相乘后返回0
原创粉丝点击