Flip Bits 181
Question
Determine the number of bits required to flip if you want to convert integer n to integer m.
Notice
Both n and m are 32-bit integers.
Example
Given n = 31 (11111), m = 14 (01110), return 2.
Solution
对a和b取^操作,如果a和b的某一位上不同则结果的那一位上为1,相同为0。然后只要依次看结果有几位1(不同)即可。
代码如下:
class Solution {
/**
*@param a, b: Two integer
*return: An integer
*/
public static int bitSwapRequired(int a, int b) {
// write your code here
int count = 0;
for(int c = a ^ b; c != 0; c = c >>> 1){
count += c & 1;
}
return count;
}
};