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
- Read the number as a string so each digit and its position are directly available. Sum all digit values first.
- 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.
- 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.
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";
}