cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2012 · EasyExpression parsing

Evaluate Plus and Minus

National Olympiad — National round (2012 season)

Submission name: expr.cpp

Problem summary

Evaluate an expression of nonnegative integers separated by + and −. Spaces may surround numbers and operators.

Input

One line containing the expression. Operators occur only between numbers.

Output

The integer value of the expression.

Constraints

Expression length ≤ 100; each number has at most 6 digits.

Worked example

An independently prepared example for this explanation.

Input

15-5+20

Output

30

Solution analysis

  1. Read the first integer into the running result. Every remaining item consists of an operator followed by a nonnegative integer.
  2. Formatted extraction skips spaces, so reading char then long long handles both compact and spaced expressions. Apply each operation immediately.
  3. For 15−5+20, start at 15, subtract 5 to get 10, then add 20 to obtain 30.

Why it works

Addition and subtraction have equal precedence and are evaluated left to right. After each operator and number, the running result is exactly the value of the processed prefix; hence the final value is correct.

Complexity: O(L) time for L characters; O(1) extra space.

Watch out. Values may become negative. Do not treat spaces as expression tokens.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
using namespace std;
int main() {
    long long result, value;
    cin >> result;
    char operation;
    // Extraction skips optional spaces around the next operator and number.
    while (cin >> operation >> value) {
        if (operation == '+') {
            result += value;
        } else {
            result -= value;
        }
    }
    cout << result << '\n';
}

Source: Arena Olimpiici ↗