You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order , and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
var addTwoNumbers = function (l1, l2) {
let dummy = new ListNode(0);
let p = dummy;
let p1 = l1;
let p2 = l2;
let carry = 0;
while (p1 || p2) {
let sum = carry;
sum += p1 ? p1.val : 0;
sum += p2 ? p2.val : 0;
carry = parseInt(sum / 10);
p.next = new ListNode(sum % 10);
p = p.next;
p1 ? p1 = p1.next : {};
p2 ? p2 = p2.next : {};
}
if (carry > 0) p.next = new ListNode(carry) // do not forget this one
return dummy.next;
};
请点击下方图片观看讲解视频
Click below image to watch YouTube Video
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order , and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Example 2:
Example 3:
Constraints:
[1, 100]
.0 <= Node.val <= 9
这道并不是什么难题,算法很简单,链表的数据类型也不难,就是建立一个新链表,然后把输入的两个链表从头往后撸,每两个相加,添加一个新节点到新链表后面。为了避免两个输入链表同时为空,我们建立一个 dummy 结点,将两个结点相加生成的新结点按顺序加到 dummy 结点之后,由于 dummy 结点本身不能变,所以用一个指针 cur 来指向新链表的最后一个结点。好,可以开始让两个链表相加了,这道题好就好在最低位在链表的开头,所以可以在遍历链表的同时按从低到高的顺序直接相加。while 循环的条件两个链表中只要有一个不为空行,由于链表可能为空,所以在取当前结点值的时候,先判断一下,若为空则取0,否则取结点值。然后把两个结点值相加,同时还要加上进位 carry。然后更新 carry,直接 sum/10 即可,然后以 sum%10 为值建立一个新结点,连到 cur 后面,然后 cur 移动到下一个结点。之后再更新两个结点,若存在,则指向下一个位置。while 循环退出之后,最高位的进位问题要最后特殊处理一下,若 carry 为1,则再建一个值为1的结点,代码如下:
C++ 解法:
Java 解法:
在 CareerCup 上的这道题还有个 Follow Up,把链表存的数字方向变了,原来是表头存最低位,现在是表头存最高位,请参见我的另一篇博客 2.5 Add Two Numbers 两个数字相加 。
Github 同步地址:
#2
类似题目:
Multiply Strings
Add Binary
Sum of Two Integers
Add Strings
Add Two Numbers II
参考资料:
https://leetcode.com/problems/add-two-numbers/
https://leetcode.com/problems/add-two-numbers/discuss/997/c%2B%2B-Sharing-my-11-line-c%2B%2B-solution-can-someone-make-it-even-more-concise
LeetCode All in One 题目讲解汇总(持续更新中...)
(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~)
喜欢请点赞,疼爱请打赏❤️~.~
微信打赏
|
Venmo 打赏
---|---
The text was updated successfully, but these errors were encountered: