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 f2bee5b

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

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

‎CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ project(Leetcode_Solution_C_C__)
33

44
set(CMAKE_CXX_STANDARD 14)
55

6-
add_executable(Leetcode_Solution_C_C__ main.cpp code/_19/Solution.cpp code/common/ListNode.h)
6+
add_executable(Leetcode_Solution_C_C__ main.cpp code/_19/Solution.cpp code/common/ListNode.hcode/_445/Solution.cpp)

‎code/_445/Solution.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//
2+
// Created by DHL on 2022年4月27日.
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 Solution {
16+
public:
17+
ListNode *reverse(ListNode *head) {
18+
ListNode *pre = nullptr;
19+
while (head) {
20+
ListNode *next = head->next;
21+
head->next = pre;
22+
pre = head;
23+
head = next;
24+
}
25+
return pre;
26+
}
27+
28+
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
29+
ListNode *p1 = reverse(l1);
30+
ListNode *p2 = reverse(l2);
31+
int carry = 0;
32+
ListNode *head = nullptr;
33+
while ((p1 || p2)) {
34+
int a = p1 ? p1->val : 0;
35+
int b = p2 ? p2->val : 0;
36+
int sum = a + b + carry;
37+
carry = sum / 10;
38+
ListNode *node = new ListNode(sum % 10);
39+
node->next = head;
40+
head = node;
41+
p1 = p1 ? p1->next : nullptr;
42+
p2 = p2 ? p2->next : nullptr;
43+
}
44+
if (carry > 0) {
45+
ListNode *node = new ListNode(carry);
46+
node->next = head;
47+
head = node;
48+
}
49+
return head;
50+
}
51+
52+
};

0 commit comments

Comments
(0)

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