未验证 提交 1cf14b1d 编写于 作者: z2014z's avatar z2014z 提交者: GitHub

Update 0002-Add-Two-Numbers.md

添加Java、Python代码实现
上级 3daa1877
......@@ -32,7 +32,8 @@
### 代码实现
```
#### C++
```c++
/// 时间复杂度: O(n)
/// 空间复杂度: O(n)
/**
......@@ -70,7 +71,68 @@ public:
};
```
#### Java
```java
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
int carry = 0;
while(l1 != null || l2 != null)
{
int sum = carry;
if(l1 != null)
{
sum += l1.val;
l1 = l1.next;
}
if(l2 != null)
{
sum += l2.val;
l2 = l2.next;
}
// 创建新节点
carry = sum / 10;
cur.next = new ListNode(sum % 10);
cur = cur.next;
}
if (carry > 0) {
cur.next = new ListNode(carry);
}
return dummyHead.next;
}
}
```
#### Python
```python
class Solution(object):
def addTwoNumbers(self, l1, l2):
res=ListNode(0)
head=res
carry=0
while l1 or l2 or carry!=0:
sum=carry
if l1:
sum+=l1.val
l1=l1.next
if l2:
sum+=l2.val
l2=l2.next
# set value
if sum<=9:
res.val=sum
carry=0
else:
res.val=sum%10
carry=sum//10
# creat new node
if l1 or l2 or carry!=0:
res.next=ListNode(0)
res=res.next
return head
```
![](../../Pictures/qrcode.jpg)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册