We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The statement n &= (n-1) is short for n = n & (n-1). This means we are applying "bitwise AND" between n and n-1, and storing the result in n.
Every iteration of this statement reduces set-bits in n by 1. So, eventually the value of n becomes 0 when there are no set-bits left. The condition while(n) checks exactly for this, and continues to run while n is non-zero. Thus, the number of iterations of loop will be same as the number of set-bits, which is stored in variable count and returned as result.
If while(n) confuses you, replace it by while (n != 0). Both have the same effect.
Counter game
You are viewing a single comment's thread. Return to all comments →
The statement
n &= (n-1)
is short forn = n & (n-1)
. This means we are applying "bitwise AND" betweenn
andn-1
, and storing the result inn
.Every iteration of this statement reduces set-bits in
n
by 1. So, eventually the value ofn
becomes 0 when there are no set-bits left. The conditionwhile(n)
checks exactly for this, and continues to run whilen
is non-zero. Thus, the number of iterations of loop will be same as the number of set-bits, which is stored in variablecount
and returned as result.If
while(n)
confuses you, replace it bywhile (n != 0)
. Both have the same effect.