Given numbers 1 to N and A number beetwen 1 to N.
You have to erase odd or even index number to reach A. If you erase edds write 1 , else 0.
1 2 3 4 5 6 7 8 9
5
1 3 5 7 9 erased even 0
1 5 9 erased even 0
5 erased odd 1.
Can anyone solve it?
#include <iostream>
usingnamespace std;
int main()
{
int N, A, pre, post;
cout << "Input N and A: "; cin >> N >> A;
pre = A - 1; post = N - A;
while ( pre > 0 || post > 0 )
{
cout << pre % 2 << '\n';
pre /= 2;
post /= 2;
}
}
Input N and A: 9 5
0
0
1
If you need to know what is actually going on, then it's somewhat longer.
#include <iostream>
#include <vector>
#include <numeric>
usingnamespace std;
//==========================================================
vector<int> dropIt( vector<int> V, int i )
{
vector<int> result;
for( ; i < V.size(); i += 2 ) result.push_back( V[i] );
return result;
}
//==========================================================
ostream & operator << ( ostream &strm, const vector<int> &V )
{
for ( int e : V ) strm << e << " ";
return strm;
}
//==========================================================
int main()
{
int N, A, pre, post;
cout << "Input N and A: "; cin >> N >> A;
vector<int> V( N );
iota( V.begin(), V.end(), 1 );
cout << "Initial vector: " << V << '\n';
pre = A - 1; post = N - A;
while ( pre > 0 || post > 0 )
{
int digit = pre % 2;
V = dropIt( V, digit );
cout << digit << " ( vector is now " << V << ")\n";
pre /= 2;
post /= 2;
}
}
//==========================================================
Input N and A: 9 5
Initial vector: 1 2 3 4 5 6 7 8 9
0 ( vector is now 1 3 5 7 9 )
0 ( vector is now 1 5 9 )
1 ( vector is now 5 )