我这里有这段代码,我这样做是为了它可以反转整数。我的问题是我不知道这是否是我能得到的最佳解决方案。它的运行时间为 O(n)。
def int_reversed(integer):
integer = str(integer)
# turning the integer into a list
each_num = []
for i in integer:
each_num.append(i)
index_one = 0
index_final = len(integer)-1
# cheking if they are the same
while index_final > index_one:
each_num[index_one], each_num[index_final] =each_num[index_final], each_num[index_one]
index_one = index_one + 1
index_final = index_final - 1
return int(''.join(each_num))
我也这样做了,但我首先尝试以算法的方式来做:
def reverse_int(num):
num = str(num)
reversed_int = num[::-1]
return reversed_int
如果您想“通过算法”执行此操作,那么您可以这样做:
def reverse_int(n):
v = 0
if n < 0:
n = -n
m = -1
else:
m = 1
while n > 0:
v *= 10
v += n % 10
n //= 10
return v * m
print(reverse_int(-123))
输出:
-321