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
- Read the first integer into the running result. Every remaining item consists of an operator followed by a nonnegative integer.
- Formatted extraction skips spaces, so reading char then long long handles both compact and spaced expressions. Apply each operation immediately.
- 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.
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';
}