algo/leetcode

2. Add Two Numbers

sourmc 2024. 8. 10. 14:36

[Problem]

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.

[Solution]

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        result = ListNode()
        cursor = result
        while l1 or l2:
            l1 = l1 or ListNode()
            l2 = l2 or ListNode()
            sum = cursor.val + l1.val + l2.val
            if sum >= 10:
                cursor.next = ListNode(val = 1)
            elif l1.next or l2.next:
                cursor.next = ListNode(val = 0)
            cursor.val = sum % 10
            l1 = l1.next
            l2 = l2.next
            cursor = cursor.next

        return result

 

If l1 length is different from l2 length, I append zero into shorter list to equalize each other's length.

l1 5 7 1 2 6 9
l2 8 2 0 0 0 0

 

After making each other's lengths equal, this problem can be solved as other plus operation problems.

 

https://leetcode.com/problems/add-two-numbers/description/

'algo > leetcode' 카테고리의 다른 글

2101. Detonate the Maximum Bombs  (0) 2024.08.15
885. Spiral Matrix III  (0) 2024.08.15
322. Coin Change  (0) 2024.08.11
70. Climbing Stairs  (0) 2024.08.11
1. Two Sum  (0) 2024.08.10