Skip to content

Commit

Permalink
Merge pull request MisterBooo#110 from ztianming/patch-4
Browse files Browse the repository at this point in the history
Update 0002-Add-Two-Numbers.md
  • Loading branch information
MisterBooo authored Aug 24, 2020
2 parents 62658cc + 1cf14b1 commit 0b6bfc8
Showing 1 changed file with 64 additions and 2 deletions.
66 changes: 64 additions & 2 deletions 0002-Add-Two-Numbers/Article/0002-Add-Two-Numbers.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@

### 代码实现

```
#### C++
```c++
/// 时间复杂度: O(n)
/// 空间复杂度: O(n)
/**
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 0b6bfc8

Please sign in to comment.