Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what is "&-" mean in c++

I have never seen this symbol before in c++, how does it work?

#include <iostream>
#include <vector>
using namespace std;
void print(int i){
    vector <int> a;
    while (i){
        a.push_back(i%2);
        i/=2;
    }
    for (int i=a.size()-1; i>=0; i--)
        cout<<a[i];
}
int main() {
    
    for (int i=1000; i>0; i-=(i&-i)){
        cout<<i<<' '<<int(i&i)<<' '<<int(i&-i)<<' ';
        print(i); cout<<' '; print(int(i&-i));
        cout<<'\n';
    }
    cout<<'\n';
    for (int i=5; i<=1000; i+=(i&-i)){
        cout<<i<<' '<<int(i&-i)<<' ';
        print(i); cout<<' '; print(int(i&-i));
        cout<<'\n';
    }
    return 0;

and it result

  • 1000 1000 8 1111101000 1000
  • 992 992 32 1111100000 100000
  • 960 960 64 1111000000 1000000
  • 896 896 128 1110000000 10000000
  • 768 768 256 1100000000 100000000
  • 512 512 512 1000000000 1000000000
  • 5 1 101 1
  • 6 2 110 10
  • 8 8 1000 1000
  • 16 16 10000 10000
  • 32 32 100000 100000
  • 64 64 1000000 1000000
  • 128 128 10000000 10000000
  • 256 256 100000000 100000000
  • 512 512 1000000000 1000000000

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The expression should be read as i & (-i). This is a "hack" to get the value of the least significant set bit in i.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading