在将链表转换为数值引发错误时



我有一个问题,我想将链表转换为单个数字例如,

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

奇怪的小函数,哈哈,但这里

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

相关内容

  • 没有找到相关文章

最新更新