-
问题
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807 -
解答
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def calcNum(self, l):
num = 0
pos = 0
cur = l
while cur:
num += cur.val * pow(10, pos)
pos += 1
cur = cur.next
return num
def addTwoNumbers(self, l1, l2):
num = self.calcNum(l1) + self.calcNum(l2)
if num < 10:
return ListNode(num)
head = ListNode(0)
other = head
while num / 10 > 0:
node = ListNode(num % 10)
other.next = node
other = other.next
num = num / 10
if num < 10:
other.next = ListNode(num)
return head.next