Rank of a Five-Digit Number
National Olympiad — Municipal round
Submission name: number.cpp
Problem summary
A five-digit integer abcde qualifies when b=a+c and d=c+e. Qualifying integers are ordered increasingly and numbered from one. Find the given integer’s position, or zero if it does not qualify.
Input
One five-digit integer.
Output
Its one-based rank, or 0.
Constraints
10000 ≤ input ≤ 99999.
Worked example
An independently prepared example for this explanation.
Input
11000
Output
1
Solution analysis
- Enumerate all five-digit integers up to the input.
- Extract their digits and count those satisfying both equations.
- Return zero unless the input itself satisfies them.
Why it works
Enumeration in numeric order counts precisely all qualifying integers preceding or equal to the input.
Watch out. Leading zero is forbidden; digit sums are equalities, not arithmetic modulo ten.
Commented C++17 solution
An independently written complete program with standard headers.
// Key idea: Enumeration in numeric order counts precisely all qualifying integers preceding or equal
// to the input.
#include<iostream>
using namespace std;
bool valid(int n){
int e=n%10;
n/=10;
int d=n%10;
n/=10;
int c=n%10;
n/=10;
int b=n%10;
int a=n/10;
return b==a+c&&d==c+e;
}
int main(){
int n;
cin>>n;
if(!valid(n)){
cout<<0<<'\n';
return 0;
}
int rank=0;
for(int i=10000;i<=n;i++){
rank+=valid(i);
}
cout<<rank<<'\n';
}