我有一个问题,我想将链接列表转换为单个数字 例如,
assert 120 == list_to_number([1,2,0])
assert -120 == list_to_number([-1,-2,0])
assert 0 == list_to_number([0])
这里我为此编写了一个代码,但它遇到了错误
def list_to_number(head):
p = True
num = ''
while (head!=None):
val = str(head)
if (val.find('-') == 0):
p = False
num = num + val.replace('-','')
head = head.next
if (p == False):
return -1*int(num)
else:
return int(num)
因此错误是
ValueError: invalid literal for int() with base 10
答案 0 :(得分:1)
奇怪的小功能大声笑,但你到这里去了
def list_to_number(head):
p = True
final_number = ''
for number in head:
n = number if number > 0 else -number
final_number = int(str(final_number) + str(n))
return final_number if p else -final_number