52 lines
630 B
C++
52 lines
630 B
C++
#include<iostream>
|
||
using namespace std;
|
||
|
||
//功能:将一个十进制数转化为二进制数
|
||
void bin2(int n) {
|
||
int i,j=0;
|
||
int a[1000];
|
||
i=n;
|
||
if(i==0) {
|
||
cout<<"0"<<endl;
|
||
}
|
||
while(i) {
|
||
a[j]=i%2;
|
||
i/=2;
|
||
j++;
|
||
}
|
||
for(i=j-1; i>=0; i--)
|
||
cout<<a[i];
|
||
cout<<endl;
|
||
}
|
||
|
||
|
||
//计算二进制中1的个数
|
||
int CountBit(int x) {
|
||
int ret=0;
|
||
while(x) {
|
||
//计算十进制数为二进制数
|
||
cout<<"x= ";
|
||
bin2(x);
|
||
cout<<"x-1= ";
|
||
bin2(x-1);
|
||
cout<<"x&(x-1)= ";
|
||
|
||
bin2(x&(x-1));
|
||
|
||
cout<<endl;
|
||
|
||
ret++;
|
||
x=x&(x-1);
|
||
}
|
||
return ret;
|
||
}
|
||
|
||
|
||
int main() {
|
||
//有多少个1?
|
||
cout<<CountBit(63)<<endl;
|
||
return 0;
|
||
}
|
||
|
||
|