Update 0002-Add-Two-Numbers.md

添加Java、Python代码实现
This commit is contained in:
Zong 2020-07-29 14:13:03 +08:00 committed by GitHub
parent 3daa187704
commit 1cf14b1d54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -32,7 +32,8 @@
### 代码实现 ### 代码实现
``` #### C++
```c++
/// 时间复杂度: O(n) /// 时间复杂度: O(n)
/// 空间复杂度: 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) ![](../../Pictures/qrcode.jpg)