Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ml): $2.add-two-numbers.md #452

Merged
merged 2 commits into from
Oct 29, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 80 additions & 4 deletions problems/2.add-two-numbers.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ https://leetcode-cn.com/problems/add-two-numbers/

## 代码

- 语言支持:JS,C++
- 语言支持:JS,C++,Java,Python

JavaScript:
JavaScript Code:

```js
```js
/**
* Definition for singly-linked list.
* function ListNode(val) {
Expand Down Expand Up @@ -102,7 +102,7 @@ var addTwoNumbers = function (l1, l2) {
};
```

C++
C++ Code:

> C++代码与上面的 JavaScript 代码略有不同:将 carry 是否为 0 的判断放到了 while 循环中

Expand Down Expand Up @@ -141,6 +141,82 @@ public:
};
```


Java Code:

```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 Code:

```py
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
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

```


**复杂度分析**

- 时间复杂度:$O(N)$
Expand Down