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

2014-03-19 06:15

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

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

代码:

 1 // 5.4 Show what the code "n & (n - 1) == 0" means.
 2 #include <cstdio>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     unsigned int n;
 8     
 9     while (scanf("%u", &n) == 1) {
10         if ((n & n - 1) == 0) {
11             printf("%u is a power of 2.
", n);
12         } else {
13             printf("%u is not a power of 2.
", n);
14         }
15     }
16     
17     return 0;
18 }
原文地址:https://www.cnblogs.com/zhuli19901106/p/3610486.html