Powers of 2 using & . But how?

Revision en1, by shanto_bangladesh, 2022-06-05 03:49:23

After solving this problem, I looked to some of other's code. In several codes, I found something like this (not exactly this, it's a simplified version of that):

int n = 10; 
for(int i = 1; i<=n; i+=i& - i;)
{
cout << i << " ";
}
 

Output: 1 2 4 8

I also tried for different values of n and the program outputs powers of 2 less than or equal to n.

But how is it working? What's exactly meant by "i+=i& — i" ?

Thanks for your patience and insight.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English shanto_bangladesh 2022-06-05 03:51:31 18 (published)
en1 English shanto_bangladesh 2022-06-05 03:49:23 580 Initial revision (saved to drafts)