【題目】面試題 05.06. 整數轉換
整數轉換。編寫一個函數,確定需要改變幾個位才能將整數A轉成整數B。
示例1:
輸入:A = 29 (或者0b11101), B = 15(或者0b01111)
輸出:2
示例2:
輸入:A = 1,B = 2
輸出:2
提示:
A,B範圍在[-2147483648, 2147483647]之間
【解題思路1】Integer.bitCount()
即求A和B異或結果裏1的個數
class Solution {
public int convertInteger(int a, int b) {
return Integer.bitCount(a ^ b);
}
}
【解題思路2】位運算
class Solution {
public int convertInteger(int a, int b) {
int res = a ^ b;
int count = 0;
while(res != 0){
res &= (res - 1); //通過n&(n-1)將n最右邊的1變爲0
count++;
}
return count;
}
}