class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# 1번 풀이
# head = temp = ListNode(0)
# carry = 0
# while l1 or l2 or carry:
# temp1 = l1.val if l1 else 0
# temp2 = l2.val if l2 else 0
# tempSum = temp1 + temp2 + carry
# temp.next = ListNode(tempSum % 10)
# temp = temp.next
# carry = tempSum // 10
# if l1:
# l1 = l1.next
# if l2:
# l2 = l2.next
# return head.next
# 2번 풀이
ans = cur = ListNode(0)
temp_l1 = l1
temp_l2 = l2
while True:
if temp_l1 and temp_l2:
cur.next = ListNode(temp_l1.val + temp_l2.val)
temp_l1 = temp_l1.next
temp_l2 = temp_l2.next
cur = cur.next
elif temp_l1 and not temp_l2:
cur.next = ListNode(temp_l1.val)
temp_l1 = temp_l1.next
cur = cur.next
elif temp_l2 and not temp_l1:
cur.next = ListNode(temp_l2.val)
temp_l2 = temp_l2.next
cur = cur.next
else:
break
temp = ans.next
carry = 0
while temp:
if carry:
temp.val += carry
carry = 0
if temp.val > 9:
temp.val -= 10
carry += 1
if temp.next:
temp = temp.next
else:
if carry:
temp.next = ListNode(carry)
break
return ans.next