320x100
728x90
leetcode 문제 : https://leetcode.com/problems/add-two-numbers/
# 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
"""
num1,num2,total = 0,0,0
i,j = 0,0
while(l1):
num1 += l1.val *(10 ** i)
i += 1
l1 = l1.next
while(l2):
num2 += l2.val *(10 ** j)
j += 1
l2 = l2.next
total = num1 + num2
sum_list = list(map(int, str(total)))
last = None
for num in sum_list:
node = ListNode(num)
node.next = last
last = node
return node
1568 / 1568 test cases passed.
|
Status:
Accepted |
Runtime: 87 ms
Memory Usage: 13.5 MB
|
Submitted: 7 hours, 4 minutes ago
|
best 풀이
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListNode(0)
result_tail = result
carry = 0
while l1 or l2 or carry:
val1 = (l1.val if l1 else 0)
val2 = (l2.val if l2 else 0)
carry, out = divmod(val1+val2 + carry, 10)
result_tail.next = ListNode(out)
result_tail = result_tail.next
l1 = (l1.next if l1 else None)
l2 = (l2.next if l2 else None)
return result.next
완벽히 이해가..ㅜ
연결리스트 python 참고 : https://goforit.tistory.com/145
728x90
반응형
'코딩테스트' 카테고리의 다른 글
[kotlin] leetcode - Search Insert Position (0) | 2022.04.27 |
---|---|
[kotlin] leetcode - Binary Search (0) | 2022.04.26 |
[python/Array] leetcode - two sum 문제 (0) | 2022.04.18 |
[C언어] 두 디렉토리 비교 (0) | 2022.03.28 |
[C언어] 삼각형 경로 최대 합 찾기 (0) | 2022.03.28 |