Tensorum
YouTubeसीखना शुरू करें
LeetCode 2 · Arithmetic

Add Two Numbers

LeetCode 2 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Grade-school addition with a carry.

मध्यमLinked ListMathRecursion

मैंने Add Two Numbers (LeetCode 2) ऐसे हल किया — Arithmetic पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

The digits are stored least-significant first, which is exactly the order you add by hand. Walk both lists together, add digits plus carry, write sum % 10 and carry sum // 10.

Approach

  1. 1

    Loop while either list or the carry remains.

  2. 2

    Missing digits count as 0.

  3. 3

    Append a node with sum % 10; carry = sum // 10.

मैंने कैसे हल किया

Digit-by-digit additionPythonO(max(m,n)) time
# 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]:
        dummy = ListNode(-1)
        temp = dummy
        carry =0
        while l1 or l2 or carry!=0:
            cur_sum = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
            new_node = ListNode(cur_sum%10)
            carry = cur_sum//10
            temp.next = new_node
            temp = temp.next
            if l1:
                l1=l1.next
            if l2:
                l2=l2.next
        return dummy.next


स्टेप-थ्रू लोड हो रहा है…

Add Two Numbers — अक्सर पूछे जाने वाले प्रश्न

Add Two Numbers के पीछे intuition क्या है?

The digits are stored least-significant first, which is exactly the order you add by hand. Walk both lists together, add digits plus carry, write sum % 10 and carry sum // 10.

Add Two Numbers (LeetCode 2) कैसे हल करें?

1. Loop while either list or the carry remains. 2. Missing digits count as 0. 3. Append a node with sum % 10; carry = sum // 10.

Add Two Numbers की time और space complexity क्या है?

Time: O(max(m, n))। Space: O(max(m, n)) output। (Accepted approach: Digit-by-digit addition।)

Add Two Numbers में आम गलतियाँ क्या हैं?

Keep looping for a final carry (999 + 1).