How to Check number of Bits set in a number(integer) ?
->Whenever a number increases by one the LSB changes->By using this technique we can easily find the number of bits set in a integer
->we can use, n &= (n-1) to find the number of bits set in a integer. Lets go to the program
C or C++ Program
count = 0;while(n)
{
n &= (n-1);
count++;
}
Let us understand this Program with the help of number n = 52
count = 0n = 52(0011 0100) & 51 (0011 0011) = 48(0011 0000)
count = 1
n = 48(0011 0000) & 47 (0010 1111) = 32(0010 0000)
count = 2
n = 32(0010 0000) & 31 (0001 1111) = 0
count = 3
No comments:
Post a comment