문제
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
풀이
작은 문제(한자리 덧셈)를 해결할 수 있도록 함수를 작성한 후, 연결 리스트를 순회하면서 계산하도록 한다.
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 == None and l2 == None :
return None
if l1 == None :
l1 = ListNode(0)
if l2 == None :
l2 = ListNode(0)
val = (l1.val + l2.val) % 10
head = ListNode(val)
if l1.val + l2.val >= 10 :
if l1.next == None :
l1.next = ListNode(1)
else :
l1.next.val += 1
head.next = self.addTwoNumbers(l1.next, l2.next)
return head
'알고리즘 트레이닝 > LeetCode' 카테고리의 다른 글
104. Maximum Depth of Binary Tree (0) | 2021.03.05 |
---|---|
66. Plus One (0) | 2021.03.04 |
100. Same Tree (0) | 2020.05.11 |
88. Merge Sorted Array (0) | 2020.05.11 |
21. Merge Two Sorted Lists (0) | 2020.05.09 |