如何根据位翻转次数将整数a转为b?Python脚本求助
问题描述
参考GeeksforGeeks的ScriptA可知,将整数a=10转换为b=20需要翻转4个二进制位。本人编写Python脚本尝试仅通过a和该翻转次数得到b,但运行结果为53而非20,请求编写正确的Python脚本实现该需求。
参考ScriptA
if __name__ == '__main__': a = 10 b = 20 # Converting int to binary and counting number of bits result = bin(a ^ b).count("1") print(result)
本人编写的错误脚本
def flip_bits_to_match_count(a, count, b): flipped_a = a flips = 0 while bin(flipped_a).count("1") != count: flipped_a ^= 1 << flips flips += 1 return flipped_a == b a = 10 count = 4 b = 20 matched = flip_bits_to_match_count(a, count, b) print("Does the flipped 'a' match 'b'?", matched)
问题分析与解决
你的脚本逻辑错误,核心问题是混淆了二进制中1的个数和需要翻转的位数:
a=10的二进制是1010(含2个1),b=20的二进制是10100(同样含2个1),你试图通过翻转位让flipped_a的1的个数等于count=4,这完全偏离了目标,自然得不到b。- 正确的思路是:要从
a得到b,需要精准翻转a和b二进制位不同的位置,这些不同位的数量就是所需的翻转次数。
正确脚本1:直接从a转换得到b
def convert_a_to_b(a, b): # 计算a和b的异或值,得到所有需要翻转的位的掩码 flip_mask = a ^ b # 翻转这些位,直接得到b return a ^ flip_mask a = 10 b = 20 converted_num = convert_a_to_b(a, b) print(f"从{a}翻转后得到的数: {converted_num}") # 验证翻转次数是否为4 required_flips = bin(a ^ b).count("1") print(f"实际需要翻转的位数: {required_flips}")
正确脚本2:验证是否可通过count次翻转从a得到b
如果你的需求是验证给定的count是否能让a转换为b,可以用以下脚本:
def is_flip_count_valid(a, count, b): # 计算a到b实际需要的翻转次数 actual_flips = bin(a ^ b).count("1") return actual_flips == count a = 10 count = 4 b = 20 print(f"是否可通过翻转{count}个位从{a}得到{b}? {is_flip_count_valid(a, count, b)}")
运行结果说明
- 脚本1运行后会输出
从10翻转后得到的数: 20以及实际需要翻转的位数: 4,符合预期。 - 脚本2运行后会输出
是否可通过翻转4个位从10得到20? True,验证了次数的正确性。
内容的提问来源于stack exchange,提问作者Dev Tenji
相关产品推荐
相关产品推荐

