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