Convert decimal to binary, and count the number of 1

	int N = 11;
	int res = 0;  // 二进制中1的个数
	string ans;  // 二进制字符串
	while (N) {
    
    
		res += N & 1;
		ans += to_string(N & 1);
		N = N >> 1;
	}
	cout << res<<endl;
	reverse(ans.begin(), ans.end()); // 反转后才是真正的二进制字符串
	cout << ans;

Guess you like

Origin blog.csdn.net/qq_41623632/article/details/120310526