[2] Add Two Numbers | Leetcode Medium
문제설명
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.
결과예시
제한사항
- 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.
파이썬 코드
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode], c = 0) :
val = l1.val + l2.val + c
c = val//10
ret = ListNode(val % 10)
if( l1.next or l2.next or c != 0):
if l1.next == None:
l1.next = ListNode(0)
if l2.next == None:
l2.next = ListNode(0)
ret.next = self.addTwoNumbers(l1.next, l2.next,c)
return ret
다른사람 코드
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
res = dummy = ListNode()
carry = 0
while l1 or l2:
v1, v2 = 0, 0
if l1: v1, l1 = l1.val, l1.next
if l2: v2, l2 = l2.val, l2.next
val = carry + v1 + v2
res.next = ListNode(val%10)
res, carry = res.next, val//10
if carry:
res.next = ListNode(carry)
return dummy.next
Time: O(n)
Space: O(1)
Author And Source
이 문제에 관하여([2] Add Two Numbers | Leetcode Medium), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@yoongyum/2-Add-Two-Numbers-Leetcode-Easy저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)