7. reverse integer

def reverse(x: int): # this use the string
    if -10 < x < 10: return x
    str_x = str(x)
    if str_x[0] != '-':
        str_x = str_x[::-1]
        x = int(str_x)
    else:
        str_x = str_x[:0:-1]
        x = int(str_x)
        x = -x
    return x if -2147483648 < x < 2147483647 else 0

a1 = -123
B1 = reverse(a1)
print(B1) #-321


def reverse1(x: int): #this use the 位运算符
    y, result = abs(x), 0  # 则其数值范围为 [−2^31,  2^31 − 1]
    boundry = (1 << 31) - 1 if x > 0 else 1 << 31 #1<<31 = 2^31
    while y != 0:
        result = result * 10 + y % 10 # if y = 123, then y%=10, the result is 3
        if result > boundry:
            return 0
        y //= 10 # if y = 123, then y//=10, the result is 12
    return result if x > 0 else -res

a = 1<<31
print(a) # 2147483648
a1 = -123
B = reverse1(a) #0
print(B)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值