Erase integer

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?
You should probably use a for loop and check whether it's even or odd using %. Then you count and print.
I know algorithm yes but dont know how use loop, and i need vector? Or only loop?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <vector>
#include <numeric>
using namespace 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 )
Last edited on
Thanks
Topic archived. No new replies allowed.