[LeetCode][Python3] 2. Add Two Numbers
2018. 9. 24. 01:27 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/add-two-numbers/description/
My Solution :
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(0)
current = dummy_head
carry = 0
while l1 and l2:
val = (l1.val + l2.val + carry) % 10
carry = (l1.val + l2.val + carry) // 10
current.next = ListNode(val)
current = current.next
l1 = l1.next
l2 = l2.next
remain = l1 or l2
while remain:
val = (remain.val + carry) % 10
carry = (remain.val + carry) // 10
current.next = ListNode(val)
current = current.next
remain = remain.next
if carry:
current.next = ListNode(1)
return dummy_head.next
Comment :
위 코드는 내가 처음으로 시도했던 방법이고, while문을 중복으로 사용하는게 비 효율적이라 판단되어 좀 더 개선된 아래 코드를 만들어 보았다.
My Solution2 :
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(0)
current = dummy_head
carry = 0
while l1 or l2 or carry:
s = carry
if l1:
s += l1.val
l1 = l1.next
if l2:
s += l2.val
l2 = l2.next
current.next = ListNode(s % 10)
current = current.next
carry = s // 10
return dummy_head.next
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 101. Symmetric Tree (0) | 2018.09.27 |
---|---|
[LeetCode][Python3] 100. Same Tree (0) | 2018.09.26 |
[LeetCode][Python3] 70. Climbing Stairs (0) | 2018.09.26 |
[LeetCode][Python3] 3. Longest Substring Without Repeating Characters (0) | 2018.09.24 |
[LeetCode][Python3] 53. Maximum Subarray (0) | 2018.09.21 |
[LeetCode][Python3] 38. Count and Say (0) | 2018.09.21 |
[LeetCode][Python3] 665. Non-decreasing Array (0) | 2018.09.13 |
[LeetCode][Python3] 705. Design HashSet (0) | 2018.09.12 |
최근에 달린 댓글 최근에 달린 댓글