zoukankan      html  css  js  c++  java
  • Leetcode 445. Add Two Numbers II

    Description: You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

    Link: https://leetcode.com/problems/add-two-numbers-ii/

    Examples:

    Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 8 -> 0 -> 7

    思路: 将两个链表表示的非负值相加,结果以链表的形式返回。下面的方法时间和空间复杂度都不是很好。

    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            def get_numbers(l):
                p = l
                numbers = []
                while p:
                    numbers.append(p.val)
                    p = p.next
                value = 0
                for i, v in enumerate(numbers):
                    value += v*pow(10, len(numbers)-1-i)
                return value
            
            n1 = get_numbers(l1)
            n2 = get_numbers(l2)
            n = n1+n2
            r = ListNode(0)
            rhead = r
            for c in str(n):
                node = ListNode(int(c), None)
                r.next = node
                r = r.next
            return rhead.next

    日期: 2020-12-03  画了两天的图,我也是够了。

  • 相关阅读:
    Oracle
    Windows
    Ajax
    Ext JS
    JavaScript
    Linux中查看各文件夹大小命令du
    本地文件上传到Linux服务器的几种方法
    Mysql线程状态
    把mysql里面的一些状态输出到文件里面显示
    linux修改磁盘调度方法
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14082708.html
Copyright © 2011-2022 走看看