Add Two Numbers
LeetCode 2 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Grade-school addition with a carry.
मी 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
Loop while either list or the carry remains.
- 2
Missing digits count as 0.
- 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).