728x90
LeetCode-2
Add Two Numbers : Add Two Numbers in Linked List
note : You may assume the two numbers do not contain any leading zero, except the number 0 itself.
myAnswer
:::python
#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: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
root = head = ListNode(0)
carry = 0
while l1 or l2 or carry:
sum = 0
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
carry, val = divmod(sum+carry, 10)
head.next = ListNode(val)
head = head.next
return root.next
Result : 72ms Memory: 14mb
๋ฐ์ํ
'๐ข One step' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[leetcode-24] Swap-Nodes-In-Pairs_2 (0) | 2023.03.21 |
---|---|
[leetcode 24] Swap Nodes in Pairs (0) | 2023.03.20 |
[leetcode-206] Reverse Linked List (0) | 2023.03.15 |
[leetcode-21] Merge Two Sorted Lists (0) | 2023.03.12 |
[leetcode 234] Palindrom Linked List (0) | 2023.03.11 |