Convert Integer A to Integer B(LintCode)

题目:Determine the number of bits required to convert integer A to integer B

Example Given n = 31, m = 14,return 2

(31)10=(11111)2

(14)10=(01110)2

解题思路:

比较两个数不同的比特位个数,显然容易想到可以使用异或处理两个整数,相同的位上为0,不同的位上为1,故接下来只需将异或后1的个数求出即可。

int number_of_ones(int x) {
    int total_ones = 0;
    while (x != 0) {
      x = x & (x-1);
      total_ones++;
    }
        return total_ones;
}

public  int bitSwapRequired(int a, int b) {
    int a_xor_b = a ^ b;
    int count = number_of_ones(a_xor_b);

    return count;
}

References:

  1. Convert Integer A to Integer B

results matching ""

    No results matching ""