Files
python/TangDou/LuoGuBook/P1036_Prepare_2.cpp

36 lines
850 B
C++
Raw Normal View History

2025-08-30 18:35:01 +08:00
#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;
}