leetcode NO.2--两数相加

题目描述:

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

 

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        answer = head  # answer是头,與最後的return相呼應,為啥是繁體字了。。。
        carry = 0  # 进位
        while l1 and l2:
            add = l1.val + l2.val + carry
            if add >= 10:
                carry = 1
            else:
                carry = 0
            head.next = ListNode(add % 10)
            head = head.next
            l1 = l1.next 
            l2 = l2.next
            if l1:
                l=l1
            else:
                l=l2    

        while l:
            add = l.val + carry

            if add >= 10:
                carry = 1
            else:
                carry = 0
            head.next = ListNode(add % 10)
            head = head.next
            l = l.next

        if carry:
            head.next = ListNode(1)
        return answer.next

 

你可能感兴趣的:(Leetcode)