LeetCode12.24

作者: supermanwasd | 来源:发表于2018-12-24 22:49 被阅读0次

    Add Two Numbers

    今天的题好难呀
    You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
    You may assume the two numbers do not contain any leading zero, except the number 0 itself.
    翻译:
    您将得到两个非空链表,它们表示两个非负整数。这些数字以相反的顺序存储,它们的每个节点都包含一个数字。将这两个数字相加并以链表的形式返回。
    您可以假设这两个数字不包含任何前导零,除了数字0本身。
    Example:
    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8
    Explanation: 342 + 465 = 807.

    解析:


    Screen Shot 2018-12-24 at 10.38.31 PM.png Screen Shot 2018-12-24 at 10.38.36 PM.png

    难点在于如何写单链表

    答案:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            if l1 == None:
                return l2
            elif l2 == None:
                return l1
            
            remain = 0
            l = ListNode(None)
            result = l
            
            while l1 != None or l2 != None:
                if l1 == None:
                    l1 = ListNode(0)
                elif l2 == None:
                    l2 = ListNode(0)
                total = l1.val + l2.val + remain
                if total >=10 :
                    total = total - 10
                    remain =1
                else:
                    remain = 0
                l.next = ListNode(total)
                l1 = l1.next
                l2 = l2.next
                l = l.next
                
            if remain == 1:
                l.next = ListNode(remain)
                
            return result.next
    

    相关文章

      网友评论

        本文标题:LeetCode12.24

        本文链接:https://www.haomeiwen.com/subject/dqitlqtx.html