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
풀이 과정
2개의 링크드 리스트를 더한 결과가 저장되어 있는 링크드 리스트의 head 포인터를 반환하는 문제이다.
carry를 이용해 받아올림을 구현하여 덧셈의 결과를 저장한 새로운 링크드 리스트를 만들었다.
소스 코드
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
root = head = ListNode(0)
carry = 0
while l1 or l2 or carry:
sum_val = 0
if l1:
sum_val += l1.val
l1 = l1.next
if l2:
sum_val += l2.val
l2 = l2.next
carry, val = divmod(sum_val + carry, 10)
head.next = ListNode(val)
head = head.next
return root.next
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 328. Odd Even Linked List [Python] (0) | 2022.07.28 |
---|---|
LeetCode - 24. Swap Nodes in Pairs [Python] (0) | 2022.07.27 |
LeetCode - 206. Reverse Linked List [Python] (0) | 2022.07.27 |
LeetCode - 234. Palindrome Linked List [Python] (0) | 2022.07.23 |
LeetCode - 121. Best Time to Buy and Sell Stock [Python] (0) | 2022.07.22 |