Add Two Numbers

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.

Intuition

The problem involves adding two numbers represented by linked lists. Since the digits are stored in reverse order, we can traverse both linked lists simultaneously, add the corresponding digits along with any carry from the previous step, and construct the resulting linked list.

Approach

Initialize variables carry and dummy to 0 and a dummy node, respectively. Also, initialize current to the dummy node.
Traverse both linked lists simultaneously until reaching the end of both lists.
At each step, compute the sum of the corresponding digits along with the carry from the previous step.
Update the carry for the next step and create a new node with the current digit of the sum.
Move to the next nodes in both linked lists and the resulting linked list.
After the traversal, check if there is any remaining carry. If so, create a new node with the carry.
Return the head of the resulting linked list (dummy.next).

Complexity

  • Time complexity:

The time complexity is O(max(m, n)), where m and n are the lengths of the two linked lists. The algorithm traverses both linked lists once.

  • Space complexity:

The space complexity is O(max(m, n)) since the solution uses additional space to store the resulting linked list.

Code

# 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]:
        count = 0
        sum1 = sum2 = 0
        first , second = l1 , l2
        while first:
          val1 = first.val
          sum1 += val1 * (10 ** count)
          first = first.next
          count += 1
        temp = count

        count = 0
        while second:
          val2 = second.val
          sum2 += val2 * (10 ** count)
          second = second.next
          count += 1

        if (sum1 + sum2) // count == 0:
            total = (sum1 + sum2) % (10 ** max(temp , count))
        else:
            total = (sum1 + sum2) % (10 ** (max(temp , count) + 1))

        dummy = ListNode()
        current = dummy

        for digit in str(total)[::-1]:
          current.next = ListNode(int(digit))
          current = current.next

        return dummy.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值