40 lines
702 B
C++
40 lines
702 B
C++
#include<iostream>
|
||
using namespace std;
|
||
|
||
//计算二进制中1的个数
|
||
int CountBit(int x) {
|
||
int ret=0;
|
||
while(x) {
|
||
ret++;
|
||
x=x&(x-1);
|
||
}
|
||
/*
|
||
我们将一个整数如1100,减去1后,变成1011。整数最右边的1变成0,1后面的0都变成1,1前面的数均不变。
|
||
所以再将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;
|
||
}
|
||
|
||
|