Skip to content

Commit 0b7e89f

Browse files
committed
add LeetCode 2. 两数相加
1 parent 63c1156 commit 0b7e89f

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

链表/LeetCode 2. 两数相加.md

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 **逆序** 的方式存储的,并且它们的每个节点只能存储 一位 数字。
6+
7+
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
8+
9+
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
10+
11+
示例:
12+
13+
```css
14+
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
15+
输出:7 -> 0 -> 8
16+
原因:342 + 465 = 807
17+
```
18+
19+
来源:力扣(LeetCode)
20+
链接:https://leetcode-cn.com/problems/add-two-numbers
21+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
22+
23+
24+
## 解题思路
25+
模拟相加,创建一个新的链表,注意一下进位,由于本题按照逆序来输出的,直接从头结点开始遍历就好了,两个链表其中一个为空节点,直接置为0即可。
26+
27+
同时,要注意,最后一个进位的情况,要进行判断一下。
28+
29+
30+
```javascript
31+
/**
32+
* Definition for singly-linked list.
33+
* function ListNode(val, next) {
34+
* this.val = (val===undefined ? 0 : val)
35+
* this.next = (next===undefined ? null : next)
36+
* }
37+
*/
38+
/**
39+
* @param {ListNode} l1
40+
* @param {ListNode} l2
41+
* @return {ListNode}
42+
*/
43+
var addTwoNumbers = function (l1, l2) {
44+
let sum = 0;
45+
let head = new ListNode('head'); // 头结点
46+
let p = head;
47+
let cnt = 0; // 进位
48+
while (l1 || l2) {
49+
let ans = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + cnt;
50+
cnt = ans >= 10 ? 1 : 0;
51+
p.next = new ListNode(ans % 10);
52+
p = p.next;
53+
l1 && (l1 = l1.next);
54+
l2 && (l2 = l2.next);
55+
}
56+
cnt && (p.next = new ListNode(cnt));
57+
return head.next;
58+
};
59+
```
60+
61+
62+
## 最后
63+
文章产出不易,还望各位小伙伴们支持一波!
64+
65+
往期精选:
66+
67+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
68+
69+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
70+
71+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
72+
73+
74+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
75+
76+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
77+
78+
```javascript
79+
学如逆水行舟,不进则退
80+
```
81+
82+

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy