0
点赞
收藏
分享

微信扫一扫

统计二进制数中有多少个1

林肯公园_97cc 2022-01-31 阅读 37
c++
#include <iostream>
using namespace std;
int lowbit(int x)
{
	return x & (-x);
}
int main()
{
	int n = 0;
	int res = 0;//用于统计二进制中的1
	cin >> n;  

	//先输出n的二进制
	for (int i = 7; i >= 0; i--) cout << (n >> i & 1);
	cout << endl;
	
	while (n)
	{
		n -= lowbit(n);
		res++;
	}
	cout << res << endl;
	return 0;
}

(代码来自yxc)

举报

相关推荐

0 条评论