Блог пользователя shanto_bangladesh

Автор shanto_bangladesh, история, 2 года назад, По-английски

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.

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
2 года назад, # |
Rev. 3   Проголосовать: нравится +1 Проголосовать: не нравится

i & (-i) is a bit trick for computing the least significant bit of i.

That said, if we are only concerned with powers of 2, i & (-i) is redundant because i & (-i) = i (powers of 2 has only 1 bit set).

If you are wondering why i & (-i) computes the least significant bit, you should learn about how two's complement works.