Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 4af61ad

Browse files
committedFeb 27, 2025
Add solution #445
1 parent 24ce041 commit 4af61ad

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,7 @@
353353
441|[Arranging Coins](./0441-arranging-coins.js)|Easy|
354354
442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium|
355355
443|[String Compression](./0443-string-compression.js)|Medium|
356+
445|[Add Two Numbers II](./0445-add-two-numbers-ii.js)|Medium|
356357
448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy|
357358
450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium|
358359
451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium|

‎solutions/0445-add-two-numbers-ii.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 445. Add Two Numbers II
3+
* https://leetcode.com/problems/add-two-numbers-ii/
4+
* Difficulty: Medium
5+
*
6+
* You are given two non-empty linked lists representing two non-negative integers. The most
7+
* significant digit comes first and each of their nodes contains a single digit. Add the two
8+
* numbers and return the sum as a linked list.
9+
*
10+
* You may assume the two numbers do not contain any leading zero, except the number 0 itself.
11+
*/
12+
13+
/**
14+
* Definition for singly-linked list.
15+
* function ListNode(val, next) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.next = (next===undefined ? null : next)
18+
* }
19+
*/
20+
/**
21+
* @param {ListNode} l1
22+
* @param {ListNode} l2
23+
* @return {ListNode}
24+
*/
25+
var addTwoNumbers = function(l1, l2) {
26+
const s1 = [];
27+
const s2 = [];
28+
let carry = 0;
29+
let head = null;
30+
31+
while (l1) {
32+
s1.push(l1.val);
33+
l1 = l1.next;
34+
}
35+
36+
while (l2) {
37+
s2.push(l2.val);
38+
l2 = l2.next;
39+
}
40+
41+
while (s1.length || s2.length || carry) {
42+
const sum = (s1.pop() || 0) + (s2.pop() || 0) + carry;
43+
carry = sum / 10 | 0;
44+
head = Object.assign(new ListNode(sum % 10), { next: head });
45+
}
46+
47+
return head;
48+
};

0 commit comments

Comments
 (0)
Please sign in to comment.