1. 程式人生 > >【python3】leetcode 2. Add Two Numbers (Medium)

【python3】leetcode 2. Add Two Numbers (Medium)

 2. Add Two Numbers (Medium)

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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

寫了一個加法器Or2

# 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
        """
        A = [];B = []
        while(l1):
            A.append(l1)
            l1 = l1.next
        while(l2):
            B.append(l2)
            l2 = l2.next 
        head = ListNode((A[0].val + B[0].val) % 10)
        cphead = head
        tag = 1 if (A[0].val + B[0].val) >=10 else 0
        n = min(len(A),len(B))
        for i in range(1,n):
            sum = A[i].val + B[i].val + tag
            head.next = ListNode(sum%10)
            tag = 1 if sum >=10 else 0
            head = head.next
        if len(A)>len(B):
            for i in range(n,len(A)):
                sum = tag + A[i].val
                head.next = ListNode(sum%10)
                tag = 1 if sum >=10 else 0
                head = head.next
                
        elif len(B)>len(A):
             for i in range(n,len(B)):
                sum = tag + B[i].val
                head.next = ListNode(sum%10)
                tag = 1 if sum >=10 else 0
                head = head.next
        if tag == 1: head.next = ListNode(1)     
        return cphead