• leetcode1


    题目链接:https://leetcode-cn.com/problems/add-two-numbers/

    代码:

     1 class ListNode:
     2     def __init__(self, x, _next = None):
     3         self.val = x
     4         self.next = _next
     5 
     6 
     7 class Solution:
     8     def addTwoNumber(self, l1:ListNode, l2:ListNode) -> ListNode:
     9         self.l1 = l1
    10         self.l2 = l2
    11         targetList = None
    12         temp = []
    13 
    14         data_carry = 0
    15         while l1 != None and  l2 != None:
    16             data_sum = (l1.val + l2.val + data_carry) % 10
    17             data_carry = (l1.val + l2.val + data_carry) // 10
    18             temp.append(data_sum)
    19             l1 = l1.next
    20             l2 = l2.next
    21         
    22         while l1 != None:
    23             data_sum = (l1.val + data_carry) % 10
    24             data_carry = (l1.val + data_carry) // 10
    25             temp.append(data_sum)
    26             l1 = l1.next 
    27         
    28         while l2 != None:
    29             data_sum = (l2.val + data_carry) % 10
    30             data_carry = (l2.val + data_carry) // 10
    31             temp.append(data_sum)
    32             l2 = l2.next
    33     
    34         if data_carry != 0:
    35             temp.append(data_carry)
    36             
    37         for i in range(len(temp)):
    38             targetList = ListNode(temp[-i-1], targetList)
    39         
    40         return targetList
    41 
    42 
    43 if __name__ == '__main__':
    44     ln1 = ListNode(3, None)
    45     ln1 = ListNode(4, ln1)
    46     ln1 = ListNode(2, ln1)
    47     # ln1 = ListNode(7, ln1)
    48     # ln1 = ListNode(8, ln1)
    49     # ln1 = ListNode(9, ln1)
    50 
    51     ln2 = ListNode(4, None)
    52     ln2 = ListNode(6, ln2)
    53     ln2 = ListNode(5, ln2)
    54     # ln2 = ListNode(7, ln2)
    55     # ln2 = ListNode(8, ln2)
    56     # ln2 = ListNode(9, ln2)
    57 
    58     sol = Solution()
    59     s = sol.addTwoNumber(ln1, ln2)
    60 
    61     print('input1 = ', end = '')
    62     while ln1 != None:
    63         print(ln1.val, end = '')
    64         ln1 = ln1.next
    65     print()
    66 
    67     print('input2 = ', end = '')
    68     while ln2 != None:
    69         print(ln2.val,end = '')
    70         ln2 = ln2.next
    71     print()
    72 
    73     print('output = ', end = '')
    74     while s != None:
    75         print(s.val, end = '')
    76         s = s.next
    77     print()
  • 相关阅读:
    Leetcode 257. 二叉树的所有路径
    Leetcode 1306. 跳跃游戏 III
    Leetcode 编程中好用的一些C++用法
    Leetcode 96. 不同的二叉搜索树
    Leetcode 892. 三维形体的表面积
    Leetcode 219. 存在重复元素 II
    Leetcode 5281. 使结果不超过阈值的最小除数
    springboot多租户设计
    MAC电脑修改Terminal以及vim高亮显示
    基于springboot搭建的web系统架构
  • 原文地址:https://www.cnblogs.com/tbgatgb/p/10845735.html
Copyright © 2020-2023  润新知