2. Add Two Numbers - python3

2024 ワード

2. 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 assume the two numbers do not contain any leading zero, except the number 0 itself.

My Answer 1: Accepted (Runtime: 72 ms - 51.16% / Memory Usage: 14.2 MB - 73.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: ListNode, l2: ListNode) -> ListNode:
        first = 0
        second = 0
        
        i = 1
        while l1:
            first += l1.val*i
            l1 = l1.next
            i *= 10
        
        i = 1
        while l2:
            second += l2.val*i
            l2 = l2.next
            i *= 10
        
        addTwo = str(first + second)
        result = ListNode(0)
        temp = result
        for i in range(len(addTwo)-1, -1, -1):
            temp.next = ListNode(addTwo[i])
            temp = temp.next
        
        return result.next
  • l 1およびl 2をintに変換し、addTwoにstr形式で
  • 保存する.
  • addTwoの一番後ろから見て、結果の
  • を入れます.

    Solution 1: Runtime: 64 ms - 89.38% / Memory Usage: 14.2 MB - 90.64%

    # 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: ListNode, l2: ListNode) -> ListNode:
            carry = 0
            root = curr = ListNode(0)
            while l1 or l2 or carry:
                if l1: carry += l1.val; l1 = l1.next
                if l2: carry += l2.val; l2 = l2.next
                curr.next = curr = ListNode(carry % 10)
                carry //= 10
            return root.next
    carryを使用したシンプルなソリューション
    暗記しなきゃ.