gavanwanggw

导航

怎样推断一个数的二进制有多少个1

以下给出计算代码:
<pre name="code" class="cpp">#include <iostream>

using namespace std;

int foo(int x)
{
	int count = 0;
	while(x)
	{
		count++;
		x = x&(x - 1);
	}
	return count;
}

int main()
{
	cout << foo(500) << endl;
        return 0;
}




举一反三 怎样推断一个数是不是2的N次方, 。(x&(x-1)

   

posted on 2017-05-25 14:38  gavanwanggw  阅读(118)  评论(0编辑  收藏  举报