• leetcode 链表 两数相加


     两数相加
     
     

    给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

    你可以假设除了数字 0 之外,这两个数字都不会以零开头。

    示例:

    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    原因:342 + 465 = 807

     1 # Definition for singly-linked list.
     2 class ListNode:
     3     def __init__(self, x):
     4         self.val = x
     5         self.next = None
     6 
     7 
     8 class Solution:
     9     def addTwoNumbers(self, l1, l2):
    10         """
    11         :type l1: ListNode
    12         :type l2: ListNode
    13         :rtype: ListNode
    14         """
    15         head = ListNode(0)
    16         cur = head
    17         m = 0
    18         while True:
    19             if l1 is not None:
    20                 a = l1.val
    21             else:
    22                 a = 0
    23             if l2 is not None:
    24                 b = l2.val
    25             else:
    26                 b = 0
    27             if l1 is None and l2 is None and m == 0:
    28                 return head.next
    29             else:
    30                 add = a + b + m
    31                 cur.next = ListNode(add % 10)
    32                 m = (a+b+m) // 10
    33                 cur = cur.next
    34             if l1 is not None:
    35                 l1 = l1.next
    36             if l2 is not None:
    37                 l2 = l2.next
  • 相关阅读:
    浏览器和node中的event loop的区别
    path.resolve(dir)与path.join(__dirname,dir)的区别
    如何在typescript项目中使用eslint
    eslint无法检测ts类型错误
    todo
    brew update 卡住
    async await原理
    node的require
    Hive表头导出成csv文件
    算法--决策树
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/9601194.html
Copyright © 2020-2023  润新知