C - Happy New Year! Editorial by en_translator
Let’s enumerate the integers that satisfy the condition.
2
20
22
200
202
220
222
2000
2002
2020
2022
...
In fact, the \(K\)-th smallest integer that satisfies the condition is the binary notation of \(K\), where \(1\) is replaced by \(2\). For example, \(5=101_{(2)}\), and if we replace \(1\) with \(2\), we have \(202\), which is indeed the \(5\)-th smallest integer that satisfies the condition.
Intuitively, the reason can be described as follows.
- In the binary notation, there are \(2\) kinds of possible digits, \(0\) and \(1\); in an integer that satisfies the condition, there are \(2\) kinds of possible digits too, \(0\) and \(2\).
- For the binary notation, the number which has \(1\) in more significant place represents the larger value; for the integers that satisfy the condition, the number which has \(2\) in more significant place represents the larger value.
Now, how can we output the answer? There are several ways to do this. In the sample code, we store the result of conversion from decimal to binary as a string and substitute \(1\) with \(2\) when outputting.
Sample code (C++):
#include<bits/stdc++.h>
using namespace std;
string convert(long long x){
string res;
while(x>0){
res.push_back('0'+(x%2));
x/=2;
}
reverse(res.begin(),res.end());
return res;
}
void output(string s){
for(auto &nx : s){
if(nx=='1'){cout << '2';}
else{cout << '0';}
}
cout << '\n';
}
int main(){
long long k;
cin >> k;
output(convert(k));
return 0;
}
posted:
last update: