feat(0002_add-two-numbers): add py3 solution

This commit is contained in:
Sangeeth Sudheer 2022-04-05 05:12:46 +05:30
parent cb5e32d56d
commit b3d6848817
2 changed files with 69 additions and 0 deletions

View File

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

View File

@ -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