将链表转换为单个数字

时间:2014-02-20 14:48:31

标签: python linked-list

我想将链表转换为单个数字

例如[1,2,0]应该转换为120

同时[-1,-2,0]应转换为-120

def list_to_number(head):
    count=0
    for i in head:
        if (head[i]<0):
            count+=1
        elif(head[i]>0):
            count=0
        elif (head[i]==0):
            continue
    if (count==0):
        n = list1(head)
        return n
    else:
        n = [abs(k) for k in head]
        n = list1(head)
        return -n
    pass

def list1(head):
    n= map(str,head)
    n = "".join(n)
    n = int(n)
    return n

2 个答案:

答案 0 :(得分:1)

你在这里尝试做什么有点模棱两可,尤其是负面的迹象。然而,一个良好的开端将是:

  • 将整数转换为字符串
  • 连接字符串
  • 将大字符串转回数字

例如:

def join(X):
    return int("".join(map(str,X)))

print join([1,2,0])          # 120
print join([0,2,1])          # 21
print join([9,4,2,4,230])    # 9424230

答案 1 :(得分:1)

>>> def weird_conversion(digits):
...     return sum(n * 10**i for (i, n) in enumerate(reversed(digits)))
...
>>> weird_conversion([1, 2, 0])
120
>>> weird_conversion([-1, -2, 0])
-120
>>> weird_conversion([-1, 2, 0])
-80
>>> weird_conversion([1, -2, 0])
80