Flip bits -- Lintcode

Determine the number of bits required to flip if you want to convert integer n to integer m.

Example
Given n = 31
(11111), m = 14
(01110), return 2

Note
Both n and m are 32-bit integers.

My solution:
整体的思路是比较 a,b 两个数中共有几位不一样的 bit。
1、比较 a,b 最后一位是否一样,若相同,counter++
2、a>>1, b >>1
3、重复1,2,直到全部位比较完毕
4、返回 counter

class Solution {
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    public static int bitSwapRequired(int a, int b) {
        
        int counter = 0;
        for (int i=1; i<=32; i++) {
            if ((a & 0X1) != (b & 0X01)) counter++;
            a = a>>>1;
            b = b>>>1;
        }
        return counter;
    }
};

XOR Version:
通过 int aXb = a^b,则 a,b中不一样的 bit 则以1保存在 aXb 中。
只需要统计 aXb的二进制中1出现的次数即可。

class Solution {
 /**
 *@param a, b: Two integer
 *return: An integer
 */
     public static int bitSwapRequired(int a, int b) {
         if (a == b) {
             return 0;
         }
         int bit = a ^ b;
         int count = 0;
         // integer has 32 bits
         int number = 32;
         // you cannot just check bit > 0 in the while statement
         // because a or b maybe negative number
         while (number > 0) {
             count += bit & 1;
             bit = bit >> 1;
             number--;
         }
         return count;
     }
};

你可能感兴趣的:(Flip bits -- Lintcode)