请解释背后Kernighan的比特计数算法逻辑 [英] Please explain the logic behind Kernighan's bit counting algorithm

查看:329
本文介绍了请解释背后Kernighan的比特计数算法逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到<一读之后,此问题直接如下href="http://stackoverflow.com/questions/12380478/bits-counting-algorithm-brian-kernighan-in-an-integer-time-complexity">位在整数时间复杂度计数算法(布莱恩Kernighan的)。 Java的code的问题是

  INT COUNT_SET_BITS(INT N){
  诠释计数= 0;
    而(N!= 0){
      N'安培; =(N-1);
      算上++;
    }
 }
 

我想明白 N'放大器; =(N-1)正在实现吗?我已经看到了类似的一种结构的另一个漂亮的算法,用于检测一个数是否是2就像一个功率:

 如果(N及(N-1)== 0){
    的System.out.println(的数目是2的幂);
}
 

解决方案

通过code在调试器步进帮助了我。

如果你开始

  N = 1010101&放大器; N-1 = 1010100 =&GT; 1010100
N = 1010100&放大器; N-1 = 1010011 =&GT; 1010000
N = 1010000&放大器; N-1 = 1001111 =&GT;百万
ñ= 1000000&放大器; N-1 = 0111111 =&GT; 0000000
 

所以这个迭代4次。每次迭代递减其被设置为1的至少显著位消失以这样的方式的值。

递减被一个翻转的最低位和每一位到第一个。例如如果你有1000 .... 0000 -1 = 0111 .... 1111不管有多少位有翻转,并停在那里留下设置不变的其他位。当你和这个与 N 的最低位设置,只有最低位变为 0

This question directly follows after reading through Bits counting algorithm (Brian Kernighan) in an integer time complexity . The Java code in question is

int count_set_bits(int n) {
  int count = 0;
    while(n != 0) {
      n &= (n-1);
      count++;
    }
 }

I want to understand what n &= (n-1) is achieving here ? I have seen a similar kind of construct in another nifty algorithm for detecting whether a number is a power of 2 like:

if(n & (n-1) == 0) {
    System.out.println("The number is a power of 2");
}

解决方案

Stepping through the code in a debugger helped me.

If you start with

n = 1010101 & n-1=1010100 => 1010100
n = 1010100 & n-1=1010011 => 1010000
n = 1010000 & n-1=1001111 => 1000000
n = 1000000 & n-1=0111111 => 0000000

So this iterates 4 times. Each iteration decrements the value in such a way that the least significant bit that is set to 1 disappears.

Decrementing by one flips the lowest bit and every bit up to the first one. e.g. if you have 1000....0000 -1 = 0111....1111 not matter how many bits it has to flip and it stops there leaving any other bits set untouched. When you and this with n the lowest bit set and only the lowest bit becomes 0

这篇关于请解释背后Kernighan的比特计数算法逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆