《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的整次幂。
代码:
题目:解释(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; }
相关文章推荐
- 《Cracking the Coding Interview》——第5章:位操作——题目1
- 《Cracking the Coding Interview》——第5章:位操作——题目2
- 《Cracking the Coding Interview》——第5章:位操作——题目3
- 《Cracking the Coding Interview》——第5章:位操作——题目5
- 《Cracking the Coding Interview》——第5章:位操作——题目6
- 《Cracking the Coding Interview》——第5章:位操作——题目7
- 《Cracking the Coding Interview》——第5章:位操作——题目8
- 《Cracking the Coding Interview》——第13章:C和C++——题目8
- 《Cracking the Coding Interview》——第14章:Java——题目4
- 《Cracking the Coding Interview》——第17章:普通题——题目6
- 《Cracking the Coding Interview》——第18章:难题——题目1
- 《Cracking the Coding Interview》——第2章:链表——题目5
- 《Cracking the Coding Interview》——第4章:树和图——题目7
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目1
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目2
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目7
- 《Cracking the Coding Interview》——第14章:Java——题目5
- 《Cracking the Coding Interview》——第18章:难题——题目2
- 《Cracking the Coding Interview》——第2章:链表——题目6
- 《Cracking the Coding Interview》——第4章:树和图——题目8