Files
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

40 lines
702 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<iostream>
using namespace std;
//计算二进制中1的个数
int CountBit(int x) {
int ret=0;
while(x) {
ret++;
x=x&(x-1);
}
/*
我们将一个整数如1100减去1后变成1011。整数最右边的1变成01后面的0都变成11前面的数均不变。
所以再将1100和1011做位与运算后相当于把减1后的数末尾的1变0。
整体来说就是将整数最右边的1变成0一直到整数变为0为止。有多少个1就能有多少的操作。相比于常规解法更加简单。
*/
return ret;
}
int main() {
//计算一下12的2进制是什么
int n=12;
int i,j=0;
int a[1000];
i=n;
while(i) {
a[j]=i%2;
i/=2;
j++;
}
for(i=j-1; i>=0; i--)
cout<<a[i];
cout<<endl;
//有多少个1
cout<<CountBit(n)<<endl;
return 0;
}