You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
850 B

2 years ago
#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;
}