Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 90e60e5

Browse files
author
bohrzhang
committed
2020年01月28日
1 parent 8aed8b9 commit 90e60e5

File tree

3 files changed

+53
-30
lines changed

3 files changed

+53
-30
lines changed

‎2.LL.M-addTwoNumbers.js‎

Lines changed: 0 additions & 29 deletions
This file was deleted.

‎2.两数相加.md‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
### 描述:
2+
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
3+
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
4+
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
5+
6+
### 示例:
7+
```
8+
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
9+
输出:7 -> 0 -> 8
10+
原因:342 + 465 = 807
11+
```
12+
13+
### 解析:
14+
循环遍历l1和l2,计算当前两节点与进位标志之和,取余重置进位标志并追加计算值到新列表,循坏结束后返回最终生成的新列表。
15+
16+
时间复杂度: O(n) / 空间复杂度: O(n)
17+
18+
```javascript
19+
/**
20+
* Definition for singly-linked list.
21+
* function ListNode(val) {
22+
* this.val = val;
23+
* this.next = null;
24+
* }
25+
*/
26+
/**
27+
* @param {ListNod}
28+
* @param {ListNode} l2
29+
* @return {ListNode}
30+
*/
31+
var addTwoNumbers = function(l1, l2) {
32+
var newList = new ListNode(0),
33+
arrayList = new ListNode(0),
34+
sum = 0,
35+
tenOrNot = 0;
36+
newList.next = arrayList;
37+
38+
while(l1 || l2 || tenOrNot !==0){
39+
sum = tenOrNot + (l1 === null ? 0 : l1.val) + (l2 === null ? 0 : l2.val);
40+
l1 = (l1 !== null) ? l1.next :null;
41+
l2 = (l2 !== null) ? l2.next :null;
42+
tenOrNot = (sum>=10)? 1 : 0;
43+
44+
arrayList.next = new ListNode(sum % 10);
45+
arrayList = arrayList.next;
46+
}
47+
48+
return newList.next.next;
49+
};
50+
```

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
# LeetCode习题JS版
22

3-
[1. 两数之和(简单)](./1.两数之和.md)
3+
[1. 两数之和(简单)](./1.两数之和.md)
4+
5+
[2. 两数相加(中等)](./2.两数相加.md)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /