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", n);
12         } else {
13             printf("%u is not a power of 2.\n", n);
14         }
15     }
16     
17     return 0;
18 }

 

相关文章:

  • 2021-08-24
  • 2021-11-11
  • 2021-11-12
  • 2021-12-27
  • 2021-08-10
  • 2021-07-29
  • 2021-10-14
  • 2022-01-08
猜你喜欢
  • 2021-10-13
  • 2021-07-28
  • 2021-11-17
  • 2021-12-07
  • 2021-06-16
  • 2021-09-05
  • 2022-02-18
相关资源
相似解决方案