今天遇到了一个有趣的问题,求一个数的二进制形式中的1的个数,有以下的程序:
#include < stdio.h>
int main ()
{
int n = 0,count = 0;
scanf("%d",&n);
for(;n>0;n /= 2)
{
if( n%2 == 1)
count++;
}
printf("%d\n",count);
}
相信很多人也会写出这样的程序但是有没有想过它的bug(比如负数呢?),还有程序的优化呢? 在Peter的引导下,讨论了很多我们可以通过位运算的方式解决,比如这样:
#include < stdio.h>
int main ()
{
int n=0,count=0,i=0;
scanf("%d",&n);
for(i = 1;i <= 32;i ++)
{
if( n&1 = 1)
{
count++;
}
n=>>;
}
printf("%d\n",count);
}
或者写成这样:
#include < stdio.h>
int main ()
{
int n=0,count=0,i=0;
scanf("%d",&n);
for(i = 1;i <= 32;i ++)
{
if( n&i = 1)
{
count++;
}
}
printf("%d\n",count);
}
但是真的需要每一个都运行32次吗,程序是否可以在优化
比如用n&(n-1)的特性:
例如一个 1011&1010=1010;
1010&1001=1000;
1000&0111=0000;
是不是每一次都会去掉其中的一个1呢?
所以程序还可以这么写:
#include < stdio.h>
int main ()
{
int n=0,count=0;
scanf("%d",&n);
while(n! = 0)
{
count++;
n = n & (n - 1);
}
printf("%d\n",count);
}
这样的方式可以少循环很多的次数,计算的资源也就省下来了。
很多时候,写完了程序本以为完事了,其实程序 还是 存在 bug的。需要你的测试与思考,还有对于程序的优化你是否想得更加遥远,程序总能有更好算法,你想是否过了别人想不到的地方,只有想过了这些细节才会使你变得与众不同。