Algorithm/Leet Code
[LeetCode/Python] 2. Add Two Numbers
byolee
2020. 7. 15. 17:20
2. Add Two Numbers
Medium
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
# 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:
head = ListNode()
result = head
carry = 0
while (l1 or l2 or carry):
if l1 and l2 :
carry = (result.val + l1.val + l2.val) // 10
sum = result.val + l1.val + l2.val - (carry*10)
result.val = sum
elif l1 or l2 :
c = l1 if l1 else l2
carry = (result.val + c.val) // 10
sum = result.val + c.val - (carry*10)
elif carry :
sum = carry
carry = 0
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
result.val = sum
if l1 or l2 or carry :
result.next = ListNode(carry)
else : result.next = None
result = result.next
return head
l1과 l2의 길이가 같다는 조건이 없으므로 다른 경우도 고려해주어야 한다.
또한 길이가 같더라도 carry가 있을 수 있으므로 or로 조건을 따진다.
carry 값은 노드를 생성할 때 넣어준 carry값도 더해줘서 10으로 나눈 몫의 값을 넣어준다.
sum은 각 값들의 합에서 carry * 10을 빼준다 (carry가 있으면 10을 빼고 아니면 0을 빼는 것)
리트코드에는 익숙지 않은 Linked List 문제가 많아서 어렵긴 한데 풀면 재밌다 ㅎㅎ
https://leetcode.com/problems/add-two-numbers/
Add Two Numbers - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com