相比于遍历所有的位数进行判断,Brian Kernighan's Algorithm的优势在于,它只需要执行与1的个数相等的循环次数,即执行次数等于二进制表示中1的个数。这使得该算法在时间复杂度上更加高效。 这个算法以Brian Kernighan的名字命名,因为他在1988年的《The C Programming Language》一书中介绍了这种方法,用于计算一个整数的...
C program: Brian Kernighan's algorithm of counting set bits in an unsigned integer /* Brian Kernighan's algorithm of counting set bits*/ #include <stdio.h> #include <string.h> int countSetBits(unsigned int n) { unsigned int c; // the total bits set in n for (c = 0; n; n =...
If you have ever worked on placement or floorplanning, and probably some other areas of EDA, then you will have heard of "Kernighan and Lin". It's a partitioning algorithm. You might not even have realized that the Kernighan of Kernighan and Lin is the same person as the Kernighan of K...
Brian W. Kernighan The Go Programming Language Amazon Alan A. A. Donovan The Go Programming Language Amazon Eliyahu M. Goldratt The Goal Amazon Richard Dawkins The God Delusion Amazon Mario Puzo The Godfather Amazon Isaac Asimov The Gods Themselves Amazon John Steinbeck The Grapes of Wrath Amazon...
Brian Kernighan's Algorithm Brian Kernighan's Algorithm是一种高效计算一个整数二进制表示中1的个数的算法。它的基本思想是利用x &= x-1操作来消除一个整数x的二进制表示中最右边的1。 算法的步骤如下: 初始化一个计数器count为0。 当x不等于0时,执行以下操作:...
我们可以使用 Brian Kernighan 的算法来提高上述朴素算法的性能。这个想法是通过关闭它最右边的设置位(在计算之后)只考虑整数的设置位,因此循环的下一次迭代考虑 下一个 最右边的位。 表达方式 n & (n-1) 可用于关闭数字的最右边设置位 n.这作为表达式 n-1 翻转最右边的设置位之后的所有位 n,包括最右边的设...