转载自:http://blog.csdn.net/djb100316878/article/details/42000987

// GetOneNumber.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;


int NumberOf1(int n)
{
int count = 0;
while (n)
{
if (n&1)//如果一个整数与1做与运算的结果是1,表示该整数最右边是1,否则是0;
{
count++;
}
n = n>>1;
}

return count;
}

/*
首先把n与1做与运算,判断n的最低位是不是为1。接着把1左移一位得到2,再和n做与运算,就能判断n的次低位是不是1....这样反复左移,每次能判断
n的其中一位是不是1.

这个解法中循环的次数等于整数二进制的位数,32位的整数需要循环32次。
*/
int NumberOf1Ex(int n)
{
int count = 0;
unsigned int key = 1;
while (key)
{
if (n & key)
{
count++;
}
key = key<<1;

}
return count;
}

/*
原理:把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0,那么一个整数的二进制表示中有
多少个1,就可以进行多少次这样的操作。

*/

int NumberOf1Ex2(int n)
{
int count = 0;
while (n)
{

n = n & (n-1);
++count;
}

return count;
}


int _tmain(int argc, _TCHAR* argv[])
{

cout<<NumberOf1Ex(9)<<endl;
cout<<NumberOf1Ex2(12)<<endl;
cout<<NumberOf1Ex(-1)<<endl;


getchar();

return 0;
}

posted on 2014-12-19 08:32  叶城宇  阅读(127)  评论(0编辑  收藏  举报