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 41b92da

Browse files
committed
feat: add question #449
1 parent f2bee5b commit 41b92da

File tree

3 files changed

+47
-2
lines changed

3 files changed

+47
-2
lines changed

‎.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,4 +271,5 @@ captures/
271271
*.DS_Store
272272

273273
.MWebMetaData/
274-
gradle.properties
274+
gradle.properties
275+
cmake-build-debug/

‎code/_445/Solution.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class Solution {
3030
ListNode *p2 = reverse(l2);
3131
int carry = 0;
3232
ListNode *head = nullptr;
33-
while ((p1 || p2)) {
33+
while (p1 || p2 || carry > 0) {
3434
int a = p1 ? p1->val : 0;
3535
int b = p2 ? p2->val : 0;
3636
int sum = a + b + carry;

‎code/_445/Solution2.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//
2+
// Created by DHL on 2022年4月29日.
3+
//
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* struct ListNode {
8+
* int val;
9+
* ListNode *next;
10+
* ListNode() : val(0), next(nullptr) {}
11+
* ListNode(int x) : val(x), next(nullptr) {}
12+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
13+
* };
14+
*/
15+
class Solution2 {
16+
public:
17+
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
18+
stack<int> stack1, stack2;
19+
while (l1) {
20+
stack1.push(l1->val);
21+
l1 = l1->next;
22+
}
23+
24+
while (l2) {
25+
stack2.push(l2->val);
26+
l2 = l2->next;
27+
}
28+
int carry = 0;
29+
ListNode *head = nullptr;
30+
while (!stack1.empty() || !stack2.empty() || carry > 0) {
31+
int a = !stack1.empty() ? stack1.top() : 0;
32+
int b = !stack2.empty() ? stack2.top() : 0;
33+
int sum = a + b + carry;
34+
carry = sum / 10;
35+
ListNode *node = new ListNode(sum % 10);
36+
node->next = head;
37+
head = node;
38+
if (!stack1.empty()) stack1.pop();
39+
if (!stack2.empty()) stack2.pop();
40+
}
41+
return head;
42+
}
43+
44+
};

0 commit comments

Comments
(0)

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