codekofi
← All problems

Problem 138

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1struct Node {
2 int val;
3 Node* next;
4};
5
6Node* build(const vector<int>& values) {
7
8 Node stub{0, nullptr};
9 Node* tail = &stub;
10
11 for (int v : values) {
12 tail->next = new Node{v, nullptr};
13 tail = tail->next;
14 }
15
16 return stub.next;
17}
18
19vector<int> spill(Node* head) {
20
21 vector<int> out;
22
23 for (Node* p = head; p; p = p->next) {
24 out.push_back(p->val);
25 }
26
27 return out;
28}
29
30Node* combine(Node* a, Node* b) {
31
32 Node stub{0, nullptr};
33 Node* tail = &stub;
34 int carry = 0;
35
36 while (a || b || carry) {
37
38 int sum = carry;
39
40 if (a) {
41 sum += a->val;
42 a = a->next;
43 }
44
45 if (b) {
46 sum += b->val;
47 b = b->next;
48 }
49
50 carry = sum / 10;
51
52 tail->next = new Node{sum % 10, nullptr};
53 tail = tail->next;
54 }
55
56 return stub.next;
57}
58
59vector<int> solution(const vector<int>& a, const vector<int>& b) {
60
61 Node* first = build(a);
62 Node* second = build(b);
63
64 return spill(combine(first, second));
65}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.