您的位置:首页 > 其它

《Cracking the Coding Interview》——第5章:位操作——题目4

2014-03-19 06:22 471 查看
2014-03-19 06:15

题目:解释(n & (n - 1)) == 0是什么意思?

解法:n&n-1是去掉最低位‘1’的方法。根据运算符优先级,貌似用不着加那个括号,但位运算的优先级总是个模棱两可的东西,所以一般还是要加上的。去掉一个‘1’就成了0,也就是说n是2的整次幂。

代码:

// 5.4 Show what the code "n & (n - 1) == 0" means.
#include <cstdio>
using namespace std;

int main()
{
unsigned int n;

while (scanf("%u", &n) == 1) {
if ((n & n - 1) == 0) {
printf("%u is a power of 2.\n", n);
} else {
printf("%u is not a power of 2.\n", n);
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐