Flip Bits
题目:
Determine the number of bits required to flip if you want to convert integer n to integer m.
Given n = 31 (11111), m = 14 (01110), return 2.
分析:
题目很简单,但是反应的思维方法很经典
1. 如何统计how many bits are set
2. 如何处理负数
解法:
class Solution {
public:
/**
*@param a, b: Two integer
*return: An integer
*/
int bitSwapRequired(int a, int b) {
// write your code here
unsigned temp = a ^ b;
int res = 0;
while (temp) {
res += temp & 1;
temp = temp >> 1;
}
return res;
}
};