181-将整数A转换为B

如果要将整数A转换为B,需要改变多少个bit位?

注意事项

Both n and m are 32-bit integers.

样例

如把31转换为14,需要改变2个bit位。
(31)10=(11111)2
(14)10=(01110)2

标签

比特位操作 Cracking The Coding Interview

思路

逐位判断即可

code

class Solution {
public:
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    int bitSwapRequired(int a, int b) {
        // write your code here
        int diff = 0, pos = 1;
        for (int i = 0; i < 32; i++) {
            if ((a & pos) != (b & pos)) {
                diff++;
            }
            pos = pos << 1;
        }
        return diff;
    }
};

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-21
  • 2021-09-05
  • 2021-07-25
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-16
  • 2021-11-16
  • 2021-08-07
  • 2022-12-23
  • 2021-12-25
  • 2021-11-16
相关资源
相似解决方案