[leetcode] 2. Add Two Numbers @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/85913661

文章目录

原题

https://leetcode.com/problems/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 contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

解题思路

定义两个函数, 一个函数将链表转换为数字, 另一个函数将数字倒置, 再转化为链表
时间复杂度: O(len(l1)) + O(len(l2)) + O(len(l1+l2))
空间复杂度: O(1)

代码

# 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
        """
        def getNumber(l):
            n_str = '';
            while l:
                n_str += str(l.val)
                l = l.next
            return int(n_str[::-1])
        
        def buildListNode(n):
            # reverse the digits of n and convert it to ListNode
            n_str_reversed = str(n)[::-1]
            head = p = ListNode(0)
            for i in range(len(n_str_reversed)):
                p.next = ListNode(int(n_str_reversed[i]))
                p = p.next
            return head.next
        
        n = getNumber(l1) + getNumber(l2)
        return buildListNode(n)

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/85913661
今日推荐