Likou NO.7 Integer inversion string inversion, take the last number inversion two methods

@[TOC]Table of Contents

Topic overview

insert image description here
insert image description here

Problem analysis and code

analyze:

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

Method 1: String Inversion

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))

Method 2: Add one digit at the end each time and judge whether it is out of bounds (-2 31 , 2 31-1)

This method will not greatly improve the efficiency. Through the representation of Python's binary numbers, it can be found that Python does not have the concept of bits. Unless it is compared bit by bit, it is difficult to improve the efficiency by simply comparing with the boundary value.

Refer to the representation of Python binary numbers

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

Reference method link

Guess you like

Origin blog.csdn.net/qq_33489955/article/details/122113326