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.

44 lines
685 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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。
1100
--->1000
整体来说就是将整数最右边的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;
}