Add Two Numbers 2
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up: What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7We can cheat by turning the numbers into strings, adding them together and then creating a new linked list.
# 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:
v1 = str("")
while l1:
v1 = v1 + str(l1.val)
l1 = l1.next
v2 = ""
while l2:
v2 = v2 + str(l2.val)
l2 = l2.next
v3 = str(int(v1) + int(v2))
head = ListNode(int(v3[0]))
res = head
for i in range(1, len(v3)):
head.next = ListNode(int(v3[i]))
head = head.next
return resYour interviewer may be impressed with your ingenuity, but shortly after they'll ask you to do is another way.
The 2nd way is to use a stack.
We append our values to stacks.
We then iterate through the stacks.
We divide and calculate the modulus using divmod:
We now know what the carry is, as well as if we have carry.
We then place this in our current list node, create a new list node and go to the next one.
We then either return the 2nd to last node if our list is complete, or the last node if we had to carry.
All together we get:
Last updated
Was this helpful?