ZhangZhihui's Blog  

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 contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

 

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

 

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

 

My Solution:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: Optional[ListNode]
        :type l2: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        
        n1 = l1
        n2 = l2
        head = ListNode()
        if n1.val + n2.val < 10:
            head.val = n1.val + n2.val
            head.next = ListNode() if n1.next or n2.next else None
        else:
            head.val = n1.val + n2.val - 10
            head.next = ListNode(1, None)
        
        s = head
        while (n1 and n1.next) or (n2 and n2.next):
            s = s.next
            n1 = n1.next if n1 and n1.next else None
            n2 = n2.next if n2 and n2.next else None

            if n1 and n2:
                if s.val + n1.val + n2.val < 10:
                    s.val = s.val + n1.val + n2.val
                    s.next = ListNode() if n1.next or n2.next else None
                else:
                    s.val = s.val + n1.val + n2.val - 10
                    s.next = ListNode(1, None)
            elif n1:
                if s.val + n1.val < 10:
                    s.val = s.val + n1.val
                    s.next = ListNode() if n1.next else None
                else:
                    s.val = s.val + n1.val - 10
                    s.next = ListNode(1, None)
            elif n2:
                if s.val + n2.val < 10:
                    s.val = s.val + n2.val
                    s.next = ListNode() if n2.next else None
                else:
                    s.val = s.val + n2.val - 10
                    s.next = ListNode(1, None)
       
        return head

 

 

posted on 2025-03-21 15:38  ZhangZhihuiAAA  阅读(13)  评论(0)    收藏  举报