(1)
int Num(int n) {
int count = 0;
while (n != 0) {
if (n % 2 == 1) {
count++;
}
n = n / 2;
}
return count;
}
int main() {
printf("%d\n", Num(13));
system("pause");
return 0;
}
这个代码是存在一定问题的。倘若要求-1存储在内存中二进制1的个数,用该段代码打印出来的结果为0,但我们都知道-1在内存中是以补码的形式存储的,整型的话就有32个1。若将nt Num(int n)改为int Num(unsigned int n),就可以求了。
(2)
int Num1(unsigned int n) {
int i = 0;
int count = 0;
for (i = 0; i < 32; i++) {
if ((n & 1) != 0) {
count++;
}
n = n >> 1;
}
return count;
}
int main() {
printf("%d\n", Num1(15));
system("pause");
return 0;
}
用这段代码的话,移位需要一直移够32次,但若求像5这样的数的二进制中1的个数,仅仅只需要移动3次就够了,剩下的移位操作都是在做无用功;所以可将其优化为以下代码:移完一位后,判断当前数字是否为0,若是,则结束循环,若不是,则继续移动直至当前数字为0,才结束循环。
(3)
int Num2(unsigned int n) {
int i = 0;
int count = 0;
while(n != 0) {
if ((n & 1) != 0) {
count++;
}
n = n >> 1;
}
return count;
}
int main() {
printf("%d\n", Num2(15));
system("pause");
return 0;
}
继续优化后可得到以下代码
(4)
int Num3(unsigned int n) {
int count = 0;
while (n != 0) {
count++;
n = n & (n - 1);//每与一次就会少一个1
}
return count;
}
int main() {
printf("%d\n", Num3(15));
system("pause");
return 0;
}