/*
In GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate function for counting set bits.
cout << __builtin_popcount (4) << endl;
1 Initialize count: = 0
2 If integer n is not zero
(a) Do bitwise & with (n-1) and assign the value back to n
n: = n&(n-1)
(b) Increment count by 1
(c) go to step 2
3 Else return count
link : https://www.geeksforgeeks.org/count-set-bits-in-an-integer/
*/
unsigned int countSetBits(int n)
{
unsigned int count = 0;
while (n)
{
n &= (n-1) ;
count++;
}
return count;
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.