class Transform {
public:
    int calcCost(int A, int B) {
        // write code here
        int xorrestult = A^B;
        int count = 0;
        while(xorrestult != 0)
        {
           int current_bit = xorrestult & 1;
           count = count + current_bit;
           xorrestult = xorrestult >> 1;
        }
        return count;
    }
};

解决该问题的核心是利用位运算精准定位并统计两个数二进制位的差异,分为两步核心逻辑:

  1. 异或找差异位:对 A 和 B 执行异或(^)操作,异或规则是 “相同二进制位得 0,不同二进制位得 1”。因此异或结果中,所有值为 1 的位,就是 A 和 B 需要修改的数位。
  2. 统计 1 的个数:统计异或结果中二进制位为 1 的数量,该数量即为需要修改的数位个数。