1. 问题描述
给定整数A和B,求出将整数A转换为B,需要改变bit的位数。
2. 问题示例
把31转换为14,需要改变2个bit位,即:(31)10=(11111)2,(14)10=(01110)2。
3. 代码实现
def bit_diff_count(A, B):
count = 0
diff = A ^ B
while diff:
count += diff & 1
diff >>= 1
return count
A = 31
B = 14
result = bit_diff_count(A, B)
print(result) # 输出2
# bit_diff_count 函数计算了 A 和 B 之间的位差,即异或结果中 1 的个数,并返回这个值。