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()

 

转载于:https://www.cnblogs.com/tbgatgb/p/10845735.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值