LeetCode2. 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.

Example:

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

这道题其实思路就是附加了一个链表,两数相加,改成了三数相加,如果l1和l2相加大于10,另外一数就是 ,则另外一个链表的下一个节点的值为1,不大于10,下一个节点的值为0。其次就是特殊情况的处理。

# 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
        """
        l3 = ListNode(0)
        cur1 = ListNode(1)
        cur0 = ListNode(0)
        a_list = []
        while l1!= None or l2!= None:
            if l1.val + l2.val +l3.val >=10:
                a_list.append(l1.val +l2.val +l3.val -10)
                l3 = l3.next
                l3 = cur1
                
                
            else:
                a_list.append(l1.val+l2.val+l3.val)
                l3 = l3.next
                l3 = cur0
                
            l2 = l2.next
            l1 = l1.next
            if l1 == None and l2 != None:
                l1 = cur0
            if l1 != None and l2 == None:
                l2 = cur0
        if l3.val == 1:
            a_list.append(1)
        return a_list
                
        

代码先这样,后期刷第二遍的时候再做优化。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章