《Cracking the Coding Interview》——第5章:位操作——题目5
2014-03-19 06:24
441 查看
2014-03-19 06:22
题目:将整数A变成整数B,每次只能变一个二进制位,要变多少次呢。
解法:异或,然后求‘1’的个数。
代码:
题目:将整数A变成整数B,每次只能变一个二进制位,要变多少次呢。
解法:异或,然后求‘1’的个数。
代码:
// 5.5 Determine the number of bits required to convert integer A to B. #include <cstdio> using namespace std; int numberOfOnes(unsigned int n) { int res = 0; while (n != 0) { n = n & (n - 1); ++res; } return res; } int main() { unsigned int a, b; while (scanf("%u%u", &a, &b) == 2) { printf("%d\n", numberOfOnes(a ^ b)); } 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章:位操作——题目4
- 《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