C++-二進制數一的個數-bitcount()函數

#include<cstdio>
#include<iostream>
using namespace std;
int NumberOf1(int n){//返回二進制一的個數 注意類型 
	int count=0;
	unsigned int flag=1;//flag從1開始 每次循環左移一位 與n做&運算 判斷該位是否爲1 
	while(flag<=n){  //flag大於n 退出循環 
		if(n&flag)
		count++;
		flag=flag<<1; 
	}
	return count;
}
int main(){
	for(int i=0;i<15;i++)
	cout<<i<<" "<<NumberOf1(i)<<endl;
	system("pause");	
	return 0;
} 
#include<cstdio>
#include<iostream>
using namespace std;
int bitcount(int x){
	return x==0?0:bitcount(x/2)+(x&1);//x&1加括號 
}
int main(){
	cout<<bitcount(3);
	system("pause");
	return 0;
} 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章