#include<stdio.h>
int count_num_of_1(int n) {
int count = 0;
while (n) {
n = n & (n - 1);
count++;
}
return count;
}
int main() {
int num = 0;
scanf("%d", &num);
int n = count_num_of_1(num);
printf("%d\n", n);
return 0;
//n&(n-1)==0这个条件也可以验证是否是2的几次方:10 100 1000 ......
按位与是一个很好的算法思路:按位与1可以拆出各个二进制位;n与n-1按位与,则可以拆出含1的个数。
这是通常的简单拆解法:
int count_num_of_1(int n) {
int count = 0;
while (n) {
if (n % 2 == 1)
count++;
n /= 2;
}
return count;
}
int count_differ_bit(int m, int n) {
int i;
int count = 0;
for (i = 0; i < 32; i++) {
if (((m >> i) & 1) != ((n >> i) & 1)) //向右移动i位,按位与1
count++;
return count;
}
}
int main() {
int m = 0, n = 0;
scanf("%d %d", &m, &n);
int ret = count_differ_bit(m, n);
printf("%d\n", ret);
}