Skip to content

Commit 1cf14b1

Browse files
authoredJul 29, 2020
Update 0002-Add-Two-Numbers.md
添加Java、Python代码实现
1 parent 3daa187 commit 1cf14b1

File tree

1 file changed

+64
-2
lines changed

1 file changed

+64
-2
lines changed
 

‎0002-Add-Two-Numbers/Article/0002-Add-Two-Numbers.md

+64-2
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232

3333
### 代码实现
3434

35-
```
35+
#### C++
36+
```c++
3637
/// 时间复杂度: O(n)
3738
/// 空间复杂度: O(n)
3839
/**
@@ -70,7 +71,68 @@ public:
7071
};
7172

7273
```
73-
74+
#### Java
75+
```java
76+
class Solution {
77+
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
78+
ListNode dummyHead = new ListNode(0);
79+
ListNode cur = dummyHead;
80+
int carry = 0;
81+
82+
while(l1 != null || l2 != null)
83+
{
84+
int sum = carry;
85+
if(l1 != null)
86+
{
87+
sum += l1.val;
88+
l1 = l1.next;
89+
}
90+
if(l2 != null)
91+
{
92+
sum += l2.val;
93+
l2 = l2.next;
94+
}
95+
// 创建新节点
96+
carry = sum / 10;
97+
cur.next = new ListNode(sum % 10);
98+
cur = cur.next;
99+
100+
}
101+
if (carry > 0) {
102+
cur.next = new ListNode(carry);
103+
}
104+
return dummyHead.next;
105+
}
106+
}
107+
```
108+
#### Python
109+
```python
110+
class Solution(object):
111+
def addTwoNumbers(self, l1, l2):
112+
res=ListNode(0)
113+
head=res
114+
carry=0
115+
while l1 or l2 or carry!=0:
116+
sum=carry
117+
if l1:
118+
sum+=l1.val
119+
l1=l1.next
120+
if l2:
121+
sum+=l2.val
122+
l2=l2.next
123+
# set value
124+
if sum<=9:
125+
res.val=sum
126+
carry=0
127+
else:
128+
res.val=sum%10
129+
carry=sum//10
130+
# creat new node
131+
if l1 or l2 or carry!=0:
132+
res.next=ListNode(0)
133+
res=res.next
134+
return head
135+
```
74136

75137

76138
![](../../Pictures/qrcode.jpg)

0 commit comments

Comments
 (0)
Please sign in to comment.