From b3d68488174ceee5653dcd10a12d801a341f0d24 Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Tue, 5 Apr 2022 05:12:46 +0530 Subject: [PATCH] feat(0002_add-two-numbers): add py3 solution --- 0002_add-two-numbers/README.md | 30 ++++++++++++++++++ 0002_add-two-numbers/python3/solution.py | 39 ++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 0002_add-two-numbers/README.md create mode 100644 0002_add-two-numbers/python3/solution.py diff --git a/0002_add-two-numbers/README.md b/0002_add-two-numbers/README.md new file mode 100644 index 0000000..87a6a4c --- /dev/null +++ b/0002_add-two-numbers/README.md @@ -0,0 +1,30 @@ +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:** + +![](https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg) + + 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. \ No newline at end of file diff --git a/0002_add-two-numbers/python3/solution.py b/0002_add-two-numbers/python3/solution.py new file mode 100644 index 0000000..cd7e1db --- /dev/null +++ b/0002_add-two-numbers/python3/solution.py @@ -0,0 +1,39 @@ +# Time: O(max(m, n)) +# Space: O(max(m, n) + 1) + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: + sum_head = None + + l1ptr, l2ptr, curr = l1, l2, None + carry = 0 + + # Iterate until l1 and l2 are exhausted + while l1ptr != None or l2ptr != None: + l1val = 0 if l1ptr is None else l1ptr.val + l2val = 0 if l2ptr is None else l2ptr.val + + # Basic sum with carry on the digits + raw_sum = l1val + l2val + carry + sum_wo_carry = raw_sum % 10 + carry = 1 if raw_sum >= 10 else 0 + + if sum_head is None: + curr = ListNode(sum_wo_carry) + sum_head = curr + else: + curr.next = ListNode(sum_wo_carry) + curr = curr.next + + l1ptr = None if l1ptr is None else l1ptr.next + l2ptr = None if l2ptr is None else l2ptr.next + + if carry > 0: + curr.next = ListNode(carry) + + return sum_head