Saturday, February 27, 2016

Flip Bits

Flip Bits

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.

思路:
把两个二进制数异或以后相同位置的数字如果不同就变成了1,相同为0。例子里面n ^ m = 10001。这样我们只要把异或后的二进制数字里有多少个1数出来就可以了。(参考Count 1 in Binary)


class Solution {
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    public static int bitSwapRequired(int a, int b) {
        // write your code here
        int num = a ^ b;
        int count = 0;
        while (num != 0) {
            num = num & (num - 1);
            count ++;
        }
        return count;
    }
}