Add Two Numbers
Total Accepted: 89439 Total Submissions: 437620 Difficulty: Medium
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
https://leetcode.com/problems/add-two-numbers/
Idea: traverse two linked lists to get the numeric values they represent. Add them. Then convert to string back and save each character as linked list element.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 or not l2:
return None
digit = 0
l1_v = 0
while l1:
l1_v = l1_v + l1.val * (10 ** digit)
digit = digit + 1
l1 = l1.next
digit = 0
l2_v = 0
while l2:
l2_v = l2_v + l2.val * (10 ** digit)
digit = digit + 1
l2 = l2.next
sum_str = str(l1_v + l2_v)
head = ListNode(int(sum_str[-1]))
prev = head
for s in sum_str[:-1][::-1]:
prev.next = ListNode(int(s))
prev = prev.next
return head
Later I found that you don’t actually need such traverse three times, though time complexity is always O(N). Here is the correct concise code:
def addTwoNumbers(self, l1, l2):
dummy = cur = ListNode(0)
carry = 0
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
cur.next = ListNode(carry%10)
cur = cur.next
carry //= 10
return dummy.next
A dummy head is needed.