用python写很简单,因为它支持大数相加的运算.
直接写进位运算也比较简单
class Solution(object):
def addTwoNumbers(self, l1, l2):
def get_num(l):
x = 0
k = 0
while l:
x = x+l.val*(10**k)
l = l.next
k+=1
return x
x = get_num(l1)+get_num(l2)
new_l = ListNode(-1)
res = new_l
for each in str(x)[::-1]:
new_l.next = ListNode(int(each))
new_l = new_l.next
return res.next
class Solution(object):
def addTwoNumbers(self,l1,l2):
c,new_l = 0,ListNode(0)
res = new_l
while l1 and l2:
a = c+l1.val + l2.val
a,c = a%10,a//10
new_l.next = ListNode(a)
new_l = new_l.next
l1,l2 = l1.next,l2.next
L = l1 if l1 else l2
while L:
a = c+L.val
a,c = a%10,a//10
new_l.next = ListNode(a)
new_l = new_l.next
L = L.next
if c:new_l.next = ListNode(c)
return res.next