Add Two Numbers

Posted 你瞅啥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Add Two Numbers相关的知识,希望对你有一定的参考价值。

题目如下:

Python代码:

# Definition for singly-linked list.
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(1)
        current = ListNode(1)
        head.next = current
        flag = 0
        while l1!=None and l2!=None:
            sum = l1.val+l2.val+flag
            if sum<10:
                flag = 0
                current.next = ListNode(sum)
            else:
                flag = 1
                current.next = ListNode(sum-10)
            current = current.next
            l1 = l1.next
            l2 = l2.next
        if l1==None and l2!=None:
            print "in"
            while l2!=None:
                if flag==0:
                    current.next = ListNode(l2.val)
                else:
                    if l2.val+1<10:
                        flag = 0
                        current.next = ListNode(l2.val+1)
                    else:
                        flag = 1
                        current.next = ListNode(l2.val-9)
                l2 = l2.next
                current = current.next
        if l1!=None and l2==None:
            print "out"
            while l1!=None:
                if flag==0:
                    current.next = ListNode(l1.val)
                else:
                    if l1.val+1<10:
                        flag = 0
                        current.next = ListNode(l1.val+1)
                    else:
                        flag = 1
                        current.next = ListNode(l1.val-9)
                l1 = l1.next
                current=current.next
        if flag == 1:
            current.next = ListNode(1)
        return head.next.next
a = ListNode(1)
b = ListNode(9)
b.next = ListNode(9)
c = Solution()
c.addTwoNumbers(a,b)

 

以上是关于Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章

Add Two Numbers

2. Add Two Numbers

leetcode练习:2.Add Two Numbers

「LeetCode」0003-Add Two Numbers(Typescript)

Add Two Numbers

Add Two Numbers