首页 > 其他 > 详细

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

时间:2014-03-19 11:48:12      阅读:424      评论:0      收藏:0      [点我收藏+]

2014-03-19 06:15

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

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

代码:

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

《Cracking the Coding Inteview》——第5章:位操作——题目4,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/zhuli19901106/p/3610486.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!