当前位置:网站首页>[leetcode] integer inversion [7]

[leetcode] integer inversion [7]

2022-07-05 04:58:00 When camellia flowers bloom.

problem :  To give you one 32 Signed integer of bit x, Return to x The result of reversing the number part in

If the integer after inversion exceeds 32 The range of signed integers of bits [-(2**31), 2**31-1] , Just go back to 0

Example 1

Input : x = 123

Output : 321

Example 2

Input : x = -123

Output : -321

Example 3

Input : x = 120

Output : 21

Example 4

Input : x = 0

Output : 0

#  solution 1
def reverse(x):
    if x == 0:
        return 0
    if x > 0:
        str_x = str(x)
        str_x = str_x[::-1]
        x = int(str_x)
        if x > 2**31 - 1:
            return 0
    if x < 0:
        str_x = str(x)
        str_x = str_x[1:]
        str_x = str_x[::-1]
        x = '-' + str_x
        x = int(x)
        if x < -(2**31):
            return 0
    return x

#  solution 2
def reverse(x):
    if x == 0:
        return 0
    else:
        str_x = str(x)
        #  Judge x negative 
        if str_x[0] == '-':
            str_x = '-' + str_x[-1:-len(str_x):-1]  
            if int(str_x) < -(2**31):
                return 0
        else:
            #  Judge x In the case of positive numbers 
            str_x = str_x[-1:- (len(str_x) + 1 ):-1]
            if int(str_x) > 2**31 - 1:
                return 0
    return(int(str_x))
原网站

版权声明
本文为[When camellia flowers bloom.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050455300633.html