力扣 NO.7整数反转 字符串倒置,取末尾数倒置两种方法

@[TOC]目录

题目概述

在这里插入图片描述
在这里插入图片描述

题目解析及代码

分析:

"""
整数范围的具体值
print(int(-2**31),# -2147483648
      bin(-2**31),# -0b10000000000000000000000000000000
      int(2**31-1),# 2147483647
      bin(2**31-1)) # 0b1111111111111111111111111111111
"""

方法一:字符串倒置

def reverse(x:int) ->int:
    if -10 < x < 10:
        return x
    str_x = str(x)
    if str_x[0]=='-':
        str_x = str_x[:0:-1] #删除第一个字符(也就是符号位)倒序打印
        x = int(str_x)
        x = -x
    else:
        str_x = str_x[::-1]
        x = int(str_x)
    return x if -2147483648 < x < 2147483647 else 0
print(reverse(123))

方法二:每次在末尾添加一位数并判断其是否越界(-231 , 231-1)

此方法并不会很大的提升效率,通过Python的二进制数的表示可以发现,Python并没有位的概念,除非一位一位的比较,否则单纯与边界值比较大很难提升多少效率

参考Python二进制数的表示

def reverse_better(x:int) -> int:
    res,y = 0,abs(x)
    if x == 0:
        return 0
    else:
        boundary = 2**31-1 if x > 0 else 2**31
    while y:
        res = res * 10 + y % 10
        if res >= boundary:
            return 0
        y = y // 10
    return res if x > 0 else -res

参考方法链接

猜你喜欢

转载自blog.csdn.net/qq_33489955/article/details/122113326
今日推荐