cppAcademy
FROM LEARNING TO COMPETING

Intermediate.
Put your skills to the test.

Bulgarian Informatics Group D · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group D also includes challenging national-level problems. The six 2017 National tasks shared by Groups C and D use their existing permanent URLs. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP D2016 · EasyString parsing

Solve a Two-Term Addition Equation

National Olympiad — Municipal round (2016 season)

Submission name: abx.cpp

Problem summary

An equation is either A+X=B or X+A=B, with nonnegative known integers. Find the unknown X, which may be negative.

Input

One equation containing only digits, X, + and =.

Output

The integer value of X.

Constraints

0 ≤ A,B ≤ 1000; no spaces or extra symbols occur.

Worked example

Input and output for the worked example discussed below.

Input

X+12=3

Output

-9

Solution analysis

  1. Find the + and = positions, then split the equation into the two left-hand terms and the right-hand value B. One of the two terms is X; the other is A.
  2. Addition is commutative, so both forms give the same equation X=B−A. Parse only the numeric term rather than trying to convert X to an integer.
  3. In X+12=3, A=12 and B=3, so X=−9. In 12+X=30 the same procedure returns 18. A signed integer is necessary even though both given numbers are nonnegative.

Why it works

Both permitted input forms express A+X=B. Subtracting the known A from both sides gives the unique solution B−A. The delimiter-based parsing identifies exactly those two known values.

Complexity: O(L) time and O(L) temporary string space, where L is the equation length.

Watch out. Do not assume X is always the first term. Permit a negative result and zero-valued known terms. Never apply stoi to the X token.

Commented C++17 solution

An independently written complete program with standard headers.

#include<algorithm>
#include<array>
#include<cmath>
#include<iostream>
#include<limits>
#include<map>
#include<numeric>
#include<set>
#include<string>
#include<vector>
using namespace std;
int main(){
    string equation;
    cin>>equation;
    size_t plus=equation.find('+');
    size_t equals=equation.find('=');
    string first=equation.substr(0,plus);
    string second=equation.substr(plus+1,equals-plus-1);
    // Either position of X leads to the same subtraction.
    int known=stoi(first=="X"?second:first);
    int result=stoi(equation.substr(equals+1));
    cout<<result-known<<'\n';
}

Source: Arena Olimpiici ↗