整数的二进制表示中1的个数

题目:输入一个整数,求该整数的二进制表达中有多少个1。例如输入10,由于其二进制表示为1010,有两个1,因此输出2。

利用位运算~第二种思路很赞....

#include<iostream>
using namespace std;
int count_one_1(int num){         
	int cnt=0;
	//unsigned int i=1;
	int i=1;
	while(i){          
		if(num&i) cnt++;
		i=i<<1;
	}
	return cnt;
}
int count_one_2(int num){      //很赞的方法
	int cnt=0;
	while(num){
		num=num&(num-1);       //101 & 100 = 100; 100 & 011=0;
		cnt++;
	}
	return cnt;
}
int main(void){
	int num;
	while(cin>>num){
		cout<<"solution1:" <<count_one_1(num)<<endl;
		cout<<"solution2:" <<count_one_2(num)<<endl;
	}
	system("pause");
	return 0;
}

posted @ 2011-02-23 17:33  akawhy  阅读(934)  评论(2编辑  收藏  举报