题解 | 求int型正整数在内存中存储时1的个数
求int型正整数在内存中存储时1的个数
https://www.nowcoder.com/practice/440f16e490a0404786865e99c6ad91c9
#include <bits/stdc++.h> using namespace std; int main() { int a ; cin >> a; if (a == 0) cout << "0"; string b; while (a > 0) { b += (a % 2) ? "1" : "0"; // 取余数并转换为字符 a /= 2; } //reverse(b.begin(), b.end()); 如用于输出二进制,则需要这行代码 int c = 0; for (int i = 0; i < b.length(); i++) { if (b[i] == '1') { c = c + 1; } } cout << c; return 0; }