百度首页 | 百度空间
 
查看文章
 
x&(x-1)表达式的意义
2007年12月04日 星期二 20:13
求下面函数的返回值(微软) -- 统计1的个数
-------------------------------------
int func(int x)
{
    int countx = 0;
    while(x)
    {
        countx++;
        x = x&(x-1);
    }
    return countx;
}

假定x = 9999
10011100001111
答案: 8

思路: 将x转化为2进制,看含有的1的个数。
注: 每执行一次x = x&(x-1),会将x用二进制表示时最右边的一个1变为0,因为x-1将会将该位(x用二进制表示时最右边的一个1)变为0。




判断一个数(x)是否是2的n次方
-------------------------------------
#include <stdio.h>

int func(int x)
{
    if( (x&(x-1)) == 0 )
        return 1;
    else
        return 0;
}

int main()
{
    int x = 8;
    printf("%d\n", func(x));
}


注:
(1) 如果一个数是
2的n次方,那么这个数用二进制表示时其最高位为1,其余位为0。

(2) == 优先级高于 &

类别:C And Clib | 添加到搜藏 | 浏览() | 评论 (5)
 
最近读者:
 
网友评论:
1
2007年12月05日 星期三 10:38
int func(int x) //这里应该加上参数类型吧
{
if( (x&(x-1)) == 0 )
return 1;
else
return 0;
}
 
2
2007年12月05日 星期三 10:41
哦 不好意思 我在C++里编译的要加int
 
3
2007年12月05日 星期三 16:51
谢谢你的留言,严格意义上来说,应该加int。这样程序才算规范!这里没有int是我的疏忽!
 
4
2008年02月11日 星期一 12:09
x & (x-1)

Use the following formula to turn off the rightmost 1-bit in a word, producing 0 if none (e.g., 01011000 ==> 01010000):
x & (x-1)

This may be used to determine if an unsigned integer is a power of 2; apply the formula followed by a 0-test on the result.
 
5
2008年03月30日 星期日 22:01
如果为0的话结果错误

判断一个数(x)是否是2的n次方
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码:
 

     

©2008 Baidu