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 E2022 · EasyDigit prefix sums

A Balanced Number

National Olympiad — Regional round (2022 season)

Submission name: bnum.cpp

Problem summary

A number is balanced if, after some digit, the sum of digits up to and including that digit equals the sum of digits strictly to its right. Output the leftmost such digit and its one-based position, or 0 if none exists.

Input

One natural number N.

Output

The balancing digit and its position, or a single 0.

Constraints

1 ≤ N ≤ 10¹⁸.

Worked example

An independently prepared example for this explanation.

Input

1359

Output

5 3

Solution analysis

  1. Read the number as a string so each digit and its position are directly available. Sum all digit values first.
  2. Scan left to right, adding the current digit to a prefix sum. The suffix sum after this digit is total−prefix, so equality is easy to check. Return at the first match to enforce the leftmost rule.
  3. For 1359, the total digit sum is 18. Prefix sums 1 and 4 fail, but the prefix ending at digit 5 sums to 9, matching the suffix 9. The output is digit 5 at position 3.

Why it works

At each tested position, prefix contains exactly the inclusive left part and total−prefix contains exactly the right part. Equality therefore detects precisely a valid split. Since positions are tested increasingly, the first valid one is the leftmost.

Complexity: O(L) time and O(L) input space, with O(1) working space, for L ≤ 19 digits.

Watch out. The balancing digit belongs to the left sum. Output the digit itself as well as its one-based position. Zero digits can create multiple valid positions.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
#include <string>
using namespace std;
int main() {
    string number;
    cin >> number;
    int total = 0;
    for (char digit : number) {
        total += digit - '0';
    }
    int prefix = 0;
    for (int i = 0; i < static_cast<int>(number.size()); i++) {
        prefix += number[i] - '0';
        // The current digit is included on the left side.
        if (prefix == total - prefix) {
            cout << number[i] << ' ' << i + 1 << '\n';
            return 0;
        }
    }
    cout << "0\n";
}

Source: Arena Olimpiici ↗