輸入一個int型正整數,輸出它的二進制形式中數字1的個數


如輸入:3=====》》》二進制101            所以  輸出 =======》》》2

#include<iostream>
#include<string>
using namespace std;
void count_byte(unsigned int x)
{
	unsigned int tmp = 1;
	int countx = 0;
	for (int i = 0; i<32; i++)
	{
		if ((tmp&x) == 1)
		{
			countx++;
		}
		x = x >> 1;
	}
	cout << countx << endl;
}


int main() {

	unsigned int num;
	cin >> num;
	count_byte(num);
	return 0;
}

 

 

 9======》》》二進制00001001               1的個數=======》》》2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM