codekofi
← All problems

Problem 142

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

1int solution(const vector<string>& tokens) {
2
3 stack<int> pending;
4
5 for (const string& t : tokens) {
6
7 if (t != "+" && t != "-" && t != "*" && t != "/") {
8 pending.push(stoi(t));
9 continue;
10 }
11
12 int b = pending.top();
13 pending.pop();
14
15 int a = pending.top();
16 pending.pop();
17
18 if (t == "+") {
19 pending.push(a + b);
20 } else if (t == "-") {
21 pending.push(a - b);
22 } else if (t == "*") {
23 pending.push(a * b);
24 } else {
25 pending.push(a / b);
26 }
27 }
28
29 return pending.top();
30}

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.