Files
python/TangDou/LuoGuBook/P1036_Prepare_2.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

36 lines
850 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
//手工版本的检查二进制中1的个数的办法
int OneCount(int n) {
int cnt = 0;
for (int i = 31; i >= 0; i--)
if ((n >> i) & 1) cnt++;//固定1右移i大法好
return cnt;
}
int OneCount2(int n) {
int cnt = 0;
for (int i = 31; i >= 0; i--)
if (n & (1 << i)) cnt++;//固定n左移1大法好
return cnt;
}
int main() {
int n;
cin >> n;
int cnt = __builtin_popcount(n);
cout << "__builtin_popcount: cnt=" << cnt << endl;
int cnt2 = OneCount(n);
cout << "OneCount: cnt2=" << cnt2 << endl;
int cnt3 = OneCount2(n);
cout << "OneCount2: cnt3=" << cnt3 << endl;
if (cnt == 1) cout << "是2的整数次幂";
else cout << "不是2的整数次幂";
return 0;
}