给定一个整数 x ,返回 x 反转后的结果
def fn(x):
pass
assert fn(31) == 13
assert fn(-123) == -321
assert fn(10) == 1
题目来源 :反转数字_牛客题霸_牛客网
给定一个整数 x ,返回 x 反转后的结果
def fn(x):
pass
assert fn(31) == 13
assert fn(-123) == -321
assert fn(10) == 1
题目来源 :反转数字_牛客题霸_牛客网
s =’’
x = input(“请输入一个整数:”)
if x[0] == ‘-’:
a = x[1:] + x[0]
else:
a = x
for i in a:
s = i + s
print(int(s))
def fn(x: int):
_final = int(f"-{''.join(list(reversed([i for i in str(x)[1:]])))}") if str(x)[0] == "-" else int(
''.join(list(reversed([i for i in str(x)]))))
return _final if -(2 ** 31) <= _final <= 2 ** 31 - 1 else 0
编写代码的时候加上三个 `号 然后写上python 会给展示python格式
类似这样
def fn(x):
if str(x)[0]=="-":
c=[j for j in str(x)[1:]]
c.reverse()
return -int(’’.join([str(i) for i in c]))
else:
c = [j for j in str(x)]
c.reverse()
return int(’’.join([str(i) for i in c]))
断言没有报错,但总感觉写的有点糙
def fn(x):
x=str(x)
if x[0] =='-':
res='-'
for i in range(len(x)):
if i>0:
res=res+x[-i]
else:
res=''
for i in range(len(x)):
res=res+x[-i-1]
return int(res)
print(fn(31),fn(-123),fn(10))
assert fn(31)==13
assert fn(-123)==-321
assert fn(10)==1
def fn(x):
'''
反转整数
:param x:
:return:
'''
b=[]
res=0
c=''
if -9<=x<=9:
return x
else:
if x<=-10:
res='-'
x=abs(x)
while x>9:
a=x%10
b.append(a)
x=x//10
b.append(x)
for i in b:
c=c+str(i)
if res=='-':
res=res+c
return int(res)
else:
return int(c)
assert fn(312) == 213
assert fn(-123) == -321
assert fn(10) == 1
def fn(x):
reverse_num = int(str(abs(x))[::-1])
return 0-reverse_num if x < 0 else reverse_num
assert fn(31) == 13
assert fn(-123) == -321
assert fn(10) == 1
def fn(x):
return int(str(x)[::-1]) if x > 0 else 0 - int(str(x)[1:][::-1])
assert fn(31) == 13
assert fn(-123) == -321
assert fn(10) == 1
def fun_reverse(x):
if x > 0:
return int(str(x)[::-1])
else:
return int(str(x)[1:][::-1])
···
‘’.join(sorted(list(str(x)),reverse=True))
···
def fn(x):
L = list(str(x))
L.reverse()
return int(''.join(L)) if x>0 else int('-' + ''.join(L[:-1]))
assert fn(31) == 13
assert fn(-123) == -321
assert fn(10) == 1
def fn(x):
return int(str(x)[::-1]) if '-' not in str(x) else int('-' + str(x)[1:][::-1])
assert fn(31) == 13
assert fn(-123) == -321
assert fn(10) == 1