2014-03-19 06:22
题目:将整数A变成整数B,每次只能变一个二进制位,要变多少次呢。
解法:异或,然后求‘1’的个数。
代码:
1 // 5.5 Determine the number of bits required to convert integer A to B. 2 #include <cstdio> 3 using namespace std; 4 5 int numberOfOnes(unsigned int n) 6 { 7 int res = 0; 8 9 while (n != 0) { 10 n = n & (n - 1); 11 ++res; 12 } 13 14 return res; 15 } 16 17 int main() 18 { 19 unsigned int a, b; 20 21 while (scanf("%u%u", &a, &b) == 2) { 22 printf("%d\n", numberOfOnes(a ^ b)); 23 } 24 25 return 0; 26 }