reference:
http://www.geeksforgeeks.org/count-set-bits-in-an-integer/
Problem Definition:
Write an efficient program to count number of 1s in binary representation of an integer.
Solution:
Brian Kernighan’s Algorithm:
Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the righmost set bit). Soif we subtract a number by 1 and do bitwise & with itself (n & (n-1)), we unset the righmost set bit. If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count.
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
Code:
/* Function to get no of set bits in binary
representation of passed binary no. */
int countSetBits(int n)
{
unsigned int count = 0;
while (n)
{
n &= (n-1) ;
count++;
}
return count;
}
本文介绍了一种高效算法,用于计算整数二进制表示中1的个数。采用Brian Kernighan算法,通过循环减一并进行按位与操作来消除最右侧的1位,直至所有位被清除。
474

被折叠的 条评论
为什么被折叠?



