2. Add Two Numbers - LeetCode Solution


Linked List Math

Python 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: ListNode, l2: ListNode) -> ListNode:
        ptr1 = l1
        ptr2 = l2
        
        ans = ListNode()
        
        head = ans
        carry =0 
        
        while l1 or l2:
            
            if l2 and  not l1:
                s = str(l2.val + carry)
     
                if len(s) ==2:
                    
                    a = ListNode(int(s[1]))
                    carry = int(s[0])
                else:
                    a = ListNode(int(s))
                    carry = 0
                
                head.next = a
                head = head.next
                l2 = l2.next
            elif l1 and not l2:
                s = str( l1.val + carry)
            
                if len(s) ==2:
                    
                    a = ListNode(int(s[1]))
                    carry = int(s[0])
                else:
                    a = ListNode(int(s))
                    carry = 0
                
                head.next = a
                head = head.next
                l1 = l1.next
            
            elif l1 and l2:
                s = str(l1.val + l2.val + carry)
                print(s, l1.val, l2.val, carry)
                if len(s) ==2:
                    
                    a = ListNode(int(s[1]))
                    carry = int(s[0])
                else:
                    a = ListNode(int(s))
                    carry = 0
                
                head.next = a
                head = head.next
                l1 = l1.next
                l2 = l2.next
                
        if carry != 0:
                a = ListNode(carry)
                carry = 0
                head.next = a
                head = head.next
            
        return ans.next
                


Comments

Submit
0 Comments
More Questions

169. Majority Element
119. Pascal's Triangle II
409. Longest Palindrome
1574A - Regular Bracket Sequences
1574B - Combinatorics Homework
1567A - Domino Disaster
1593A - Elections
1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence
MAXBRIDGE Maximise the bridges
WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings
1002. Find Common Characters
1602A - Two Subsequences
1555A - PizzaForces
1607B - Odd Grasshopper
1084A - The Fair Nut and Elevator
1440B - Sum of Medians
1032A - Kitchen Utensils
1501B - Napoleon Cake
1584B - Coloring Rectangles
1562B - Scenes From a Memory
1521A - Nastia and Nearly Good Numbers
208. Implement Trie
1605B - Reverse Sort
1607C - Minimum Extraction
1604B - XOR Specia-LIS-t