Numbers containing only 0 and 6
National Olympiad — Municipal round
Submission name: round.cpp
Problem summary
List nonnegative integers whose decimal digits belong to {0,6} in increasing order, beginning with 0. Find the K-th number, using 1-based positions.
Input
K.
Output
The requested decimal number.
Constraints
1 ≤ K ≤ 1000.
Worked example
An independently prepared example for this explanation.
Input
8
Output
666
Solution analysis
- Write K−1 in binary.
- Replace each binary 1 with 6; retain each 0. Handle K=1 as 0.
Why it works
Binary order and the order of decimal strings over {0,6} agree: shorter positive strings come first, then lexicographic order within each length.
Watch out. The initial zero occupies position 1; do not convert K itself.
Commented C++17 solution
An independently written complete program with standard headers.
// Key idea: Binary order and the order of decimal strings over {0,6} agree: shorter positive strings
// come first, then lexicographic order within each length.
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main(){
int k;
cin>>k;
--k;
string s;
do{
s+=k%2?'6':'0';
k/=2;
}
while(k);
reverse(s.begin(),s.end());
cout<<s<<'\n';
}