请问大佬们,这个代码还能精简吗?(负数的处理)【python实现】

P1307 [NOIP2011 普及组] 数字反转

Rammer @ 2022-03-24 23:38:29

N = int(input())
x = 0
if(N>0):
    while(N!=0):
        a = N % 10
        x = 10*x + a
        N = N//10
    print(x)

elif(N<0):
    N *= -1
    while(N!=0):
        a = N % 10
        x = 10*x + a
        N = N//10
    print(-x)

else:print (0)

by Zpair @ 2022-03-25 00:01:45

这样?

N = int(input())
x = 0
y = N < 0
if (N < 0):
    N = -N
while(N!=0):
    a = N % 10
    x = 10*x + a
    N = N//10
if (y == 1):
    x = -x
print(x)

by Terrible @ 2022-03-25 01:00:48

@Rammer 我觉得可以精简成这样:

a=input()[::-1].lstrip('0')
if a=='':a='0'
if a[-1]=='-':a='-'+a[:-1]
print(a)

by Rammer @ 2022-03-25 09:47:10

@Zpair 确实··· 完全可以提前转化负数,省的费大篇幅再写一遍函数······


by Rammer @ 2022-03-25 09:47:44

@Terrible 好精简!这就去研究研究


|