https://leetcode.com/problems/add-two-numbers/description/
Add Two Numbers - LeetCode
Add Two Numbers - 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 as
leetcode.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
# 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
|
cs |
반응형
'python-algorithm' 카테고리의 다른 글
leetcode 328. Odd Even Linked List (0) | 2023.02.17 |
---|---|
leetcode 24. Swap Nodes in Pairs (0) | 2023.02.17 |
leetcode 206. Reverse Linked List (0) | 2023.02.17 |
백준 9772 Quadrants (0) | 2023.02.17 |
leetcode 989. Add to Array-Form of Integer (0) | 2023.02.15 |
댓글