65 lines
1.2 KiB
C++
65 lines
1.2 KiB
C++
#include <cstdint>
|
|
|
|
namespace {
|
|
|
|
struct ListNode {
|
|
int val;
|
|
ListNode *next;
|
|
ListNode() : val(0), next(nullptr) {}
|
|
ListNode(int x) : val(x), next(nullptr) {}
|
|
ListNode(int x, ListNode *next) : val(x), next(next) {}
|
|
};
|
|
|
|
class Solution {
|
|
auto getNum(ListNode* l1, ListNode* l2) -> ListNode* {
|
|
ListNode *head, *prev, *curr;
|
|
|
|
int v_ume = 0;
|
|
|
|
while (l1 || l2) {
|
|
int a = 0, b = 0;
|
|
if (l1) {
|
|
a = l1->val;
|
|
l1 = l1->next;
|
|
}
|
|
if (l2) {
|
|
b = l2->val;
|
|
l2 = l2->next;
|
|
}
|
|
|
|
int sum = a + b + v_ume;
|
|
|
|
int x = sum % 10;
|
|
v_ume = sum / 10;
|
|
|
|
curr = new ListNode(x);
|
|
if (!head) {
|
|
head = curr;
|
|
} else {
|
|
prev->next = curr;
|
|
}
|
|
prev = curr;
|
|
}
|
|
|
|
if (v_ume != 0) {
|
|
curr = new ListNode(v_ume);
|
|
prev->next = curr;
|
|
}
|
|
|
|
return head;
|
|
}
|
|
|
|
public:
|
|
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
|
|
return getNum(l1, l2);
|
|
}
|
|
};
|
|
|
|
}
|
|
|
|
#include <gtest/gtest.h>
|
|
|
|
TEST(P2, 1) {
|
|
Solution s;
|
|
auto res = s.addTwoNumbers(nullptr, nullptr);
|
|
} |