//author: Łukasz Pasek //resources: https://www.geeksforgeeks.org/count-set-bits-in-an-integer/ #include<iostream> #include<vector> #include<stack> using namespace std; int BitsSetTable256[256]; // Function to initialise the lookup table void initialize() { // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; } } // Function to return the count // of set bits in n int countSetBits(int n) { return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]); } int main() { // Initialise the lookup table initialize(); vector<int> R; int result=0; int n; int cou=0; cin>>n; int help=-1; for(int i=1 ; result!=n ; i++) { result+=countSetBits(i); R.push_back(i); cou++; //cout<<"result "<<result<<endl; if(result>n) { help=result-n; break; } } for(int i=R.size()-1 ; i>=0 ; i--) { if(help>=countSetBits(R[i])) { help-=countSetBits(R[i]); R[i]=-1; cou--; } } cout<<cou<<"\n"; for(int i=R.size()-1 ; i>=0 ; i--) { if(R[i]!=-1) cout<<R[i]<<" "; } cout<<endl; return 0; }
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | //author: Łukasz Pasek //resources: https://www.geeksforgeeks.org/count-set-bits-in-an-integer/ #include<iostream> #include<vector> #include<stack> using namespace std; int BitsSetTable256[256]; // Function to initialise the lookup table void initialize() { // To initially generate the // table algorithmically BitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; } } // Function to return the count // of set bits in n int countSetBits(int n) { return (BitsSetTable256[n & 0xff] + BitsSetTable256[(n >> 8) & 0xff] + BitsSetTable256[(n >> 16) & 0xff] + BitsSetTable256[n >> 24]); } int main() { // Initialise the lookup table initialize(); vector<int> R; int result=0; int n; int cou=0; cin>>n; int help=-1; for(int i=1 ; result!=n ; i++) { result+=countSetBits(i); R.push_back(i); cou++; //cout<<"result "<<result<<endl; if(result>n) { help=result-n; break; } } for(int i=R.size()-1 ; i>=0 ; i--) { if(help>=countSetBits(R[i])) { help-=countSetBits(R[i]); R[i]=-1; cou--; } } cout<<cou<<"\n"; for(int i=R.size()-1 ; i>=0 ; i--) { if(R[i]!=-1) cout<<R[i]<<" "; } cout<<endl; return 0; } |