7.leetcode 整数反转(简单)

leetcode python 刷题记录,从易到难


一、题目

在这里插入图片描述


二、解答

A、version1

1.思路

把数字转成字符串,调用反转方法,再转回数字

2.实现

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        try:
            return int(str(x)[::-1])
        except Exception,e:
            return 0

3.提交结果

在这里插入图片描述

4.反思

没有考虑负数的情况


B、version2

1.思路

判断是否等于负数,如果是正数就把数字转成字符串,调用反转方法,再转回数字返回;
如果是负数把数字转成字符串,调用反转方法,去掉最后的减号加在前面,再转回数字返回;

2.实现

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        try:
            str1 = str(x)[::-1]
            if str1.__contains__("-"):
                str1= "-"+str1.replace("-","")
                return int(str1)
            else:
                return int(str1)
        except Exception,e:
            return 0

3.提交结果

在这里插入图片描述

4.反思

没有实现范围的要求。数值范围为 [−231, 231 − 1]的要求。请根据这个假设,如果反转后整数溢出那么就返回 0。


C、version3(最终版本)

1.思路

判断是否等于负数,如果是正数就把数字转成字符串,调用反转方法,再转回数字。再判断数字是否大于右边界,大于则返回0,不大于则返回数字本身;
如果是负数把数字转成字符串,调用反转方法,去掉最后的减号加在前面,再转回数字。再判断数字是否大于左边界,大于则返回0,不大于则返回数字本身;

2.实现

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        try:
            str1 = str(x)[::-1]
            if str1.__contains__("-"):
                str1= "-"+str1.replace("-","")
                return 0 if int(str1) < -2147483648 else int(str1)
            else:
                return 0 if int(str1) > 2147483647 else int(str1)
        except Exception,e:
            return 0

3.提交结果

在这里插入图片描述

三、Github地址

https://github.com/m769963249/leetcode_python_solution/blob/master/easy/7.py

参考链接:

leetcode官网

猜你喜欢

转载自blog.csdn.net/qq_39945938/article/details/107142085