如果要將整數A轉換爲B,需要改變多少個bit位?
樣例
如把31轉換爲14,需要改變2個bit位。
(31)10=(11111)2
(14)10=(01110)2
挑戰
你能想出幾種方法?
solution: 這題的意思就是比較A和B中不同位的個數及相異位的個數。因此,很容易想到異或操作,及相異爲1,相同爲0。因此可以先做C = A^B,然後在計算C的二進制表示中1的個數。其中計算C中二進制1的個數時使用左移,需要特別的注意,因爲C可能爲負數,負數的右移和正數的右移是有差別的。
code
class Solution {
public:
/**
*@param a, b: Two integer
*return: An integer
*/
int bitSwapRequired(int a, int b) {
// write your code here
int c = a ^ b;
return getBitCount(c);
}
private:
int getBitCount(int a) {
int count = 0;
//因爲負數的右移是在前面填1,因此我們只需要移32就可。
for (int i = 1; i <= 32; ++i) {
count += a & 1;
a >>= 1;
}
return count;
}
};
當int型不是32位時會出現錯誤的答案,因此一種改進版本的代碼爲:
int getBitCount(int a) {
int count = 0;
while (a) {
a = a & (a - 1);
++count;
}
return count;
}