LeetCode - Daily Challenge - Add Two Numbers
Problem Description
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 contains a single digit.
Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1 :
- Input: l1 = [2,4,3], l2 = [5,6,4]
- Output: [7,0,8]
- Explanation: 342 + 465 = 807.
Example 2:
- Input: l1 = [0], l2 = [0]
- Output: [0]
Example 3:
- Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
- Output: [8,9,9,9,0,0,0,1]
Constraints:
- The number of nodes in each linked list is in the range [1, 100].
- 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
My Solution (Python)
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListNode()
answer = result # head of result
remainder = 0
sum = 0
while True:
if l1 == None and l2 == None:
if remainder == 1:
sum = 1
remainder = 0
else:
break
elif l1 == None and l2 != None:
sum = l2.val + remainder
l2 = l2.next
elif l1 != None and l2 == None:
sum = l1.val + remainder
l1 = l1.next
else:
sum = l1.val + l2.val + remainder
l1 = l1.next
l2 = l2.next
if (sum < 10):
remainder = 0
else:
sum = sum - 10
remainder = 1
result.next = ListNode(sum)
result = result.next
return answer.next
- ๋ฆฌํดํ ๋ ธ๋์ ํค๋๋ฅผ ๋ง๋ค์ด์ค๋ค. (์ด๋ ์ ์ถ์ฉ์ ์ํด answer๋ก ๋ฐ๋ก ์ ์ฅํด์ฃผ์์.)
- ๋ฐ๋ณต๋ฌธ: ๋
ธ๋๊ฐ Tail์ธ์ง ํ์ธํ๊ธฐ ์ํ if elif ... else ๋ฌธ์ ์ด์ฉํ๋ค.๊ฐ ๋
ธ๋์ ๊ฐ์ด sum์ ๋ํ๊ณ ๋ ๋ค์๋ ๋ค์ ๋
ธ๋์ ๊ฐ์ ๊ธฐ์กด์ ๋ณ์์ ์ ์ฅํ๋ค.
- ๋ ๋ ธ๋๊ฐ Tail์ผ๋, ๋จ์์๋ ๋๋จธ์ง๋ฅผ ํ์ธํ๊ณ ๋๋จธ์ง๊ฐ ์๋ค๋ฉด ๋ฐ๋ณต๋ฌธ์ ์ข ๋ฃํ๋ค.
- ๋ ๋ ธ๋ ์ค ํ๋๋ง Tail์ผ๋, Tail์ด ์๋ ๋ ธ๋์ ๊ฐ๊ณผ ๋๋จธ์ง๋ฅผ ๋ํ sum ๊ฐ์ ๊ตฌํ๋ค.
- ๋ ๋ ธ๋ ๋ค Tail์ด ์๋์ผ๋, ๋ ๋ ธ๋์ ๊ฐ๊ณผ ๋๋จธ์ง๋ฅผ ๋ํ sum ๊ฐ์ ๊ตฌํ๋ค.
- ๊ฐ ๋
ธ๋๋ 1 digit number๋ง ์ ์ฅํ ์ ์์ผ๋ฏ๋ก 10์ด ๋๋ฉด ์ผ์ ์๋ฆฌ ์๋ง ์ ์ฅํ๊ณ ๋ค์ ๋
ธ๋์ ๊ฐ์ 1์ ์ถ๊ฐํ๋ฏ๋ก if statement๋ฅผ ์ด์ฉํด ํ์ธํด์ค๋ค.
- sum ๊ฐ์ด 10 ๋ฏธ๋ง์ผ ๊ฒฝ์ฐ remainder๋ 0๊ฐ ๋๋ค.
- sum ๊ฐ์ด 10 ์ด์์ผ ๊ฒฝ์ฐ sum ์์ 10์ ๋บ ๋ค ์ผ์ ์๋ฆฌ ๊ฐ๋ง ์ ์ฅ, remainder์ 1์ ์ ์ฅํ๋ค.
- ๋ฐ๋ณต๋ฌธ์ด ์ข ๋ฃ๋๋ฉด Head์ธ answer์ ๋ค์ ๊ฐ์ธ answer.next ๊ฐ์ ๋ฆฌํดํ๋ค. (answer.val ๊ฐ์ด 0์ด๋ฏ๋ก)
'Problem solving > Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 1646. Get Maximum in Generated Array (Python) (0) | 2021.01.16 |
---|---|
[LeetCode]Daily Challenge: Boats to Save People (Python) (0) | 2021.01.13 |
[LeetCode] Daily Challenge Merge Sorted Array (Python) (0) | 2021.01.12 |
[LeetCode] 1684. Count the Number of Consistent Strings (Python) (0) | 2021.01.10 |
[LeetCode] 1678. Goal Parser Interpretation (Python) (0) | 2021.01.10 |