1


这是我今天遇到的一个笔试题,那个时候我花了大概五分钟,想到了这么一个算法,我想应该是最高效率的了,但由于紧张,写的时候还是写错了。 我现在把他写上来,看看大家有没有比这个方法更好的。

 int Count(int num)
    {
        int count = 0;
        while (true)
        {
            if ((num & -num) != 0)
                count++;
            else break;
            num &= num - 1;
        }
        return count;
    }
垃圾帖?
提问于2009-02-17 13:19:18
120 1 5
评论 (1)
1


用位运算有个陷阱:int(有符号4字节整数)最高位是负号位,而且负数是2-补位表示的 所以

int Count(int num)
{
    if (num == INT32_MIN)
        return 1;
    if (num < 0)
        return Count(-num);
    int count = 0;
    while (true)
    {
        if ((num & -num) != 0)
            count++;
        else break;
        num &= num - 1;
    }
    return count;
}
永久链接 | 垃圾帖?
回答于2009-03-30 11:03:37
70 3
添加评论
1


int count(int n) {
    int count = 0;
    while(n){
        count+=n&1;
        n>>=1;
    }
    return count;
}
永久链接 | 垃圾帖?
回答于2009-04-28 02:34:36
60 3
添加评论
0


我之前在书中看到过这道题目,但没有去想。

现在再看的时候,第一个想到的办法是算被2整除的次数,容易理解,可能大多数人也是。

永久链接 | 垃圾帖?
回答于2009-02-17 21:54:47
348 2 10
评论 (1)
0


我博客上有人给了这个回答,我觉得比我的好得多哦。

    int Count(int n)
    {
        int count = 0;
        while (n)
        {
            count++;
            n &= n - 1;
        }
        return count;
    }

作者是adrianx

永久链接 | 垃圾帖?
回答于2009-02-18 05:51:05
120 1 5
评论 (1)
0


int Count(int val)
{
    int i = 1;
    int count = 0;
    while(val>i)
    {
        if (val != (val^i))
        {
            count++;
        }
        i<<;
    }
}
永久链接 | 垃圾帖?
回答于2009-02-24 09:25:18
95 1 2
添加评论
0


int Count(unsigned x) {
    x = x - ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0F0F0F0F;
    x = x + (x >> 8);
    x = x + (x >> 16);
    return x & 0x0000003F;
}

这个是二分法,不需要循环和判断,所以效率比较高。我以前写过一篇博文介绍数1的算法,可以参考下 http://techblog.iamzellux.com/2008/04/count-1-bits-in-an-int32/

永久链接 | 垃圾帖?
回答于2010-01-20 04:24:44
1 1
添加评论




Made with Django.

当前版本: R-0127-20090523

cc-wiki