You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何同时遍历两个序列?二进制转十进制编程实现求助

二进制转十进制的匹配问题

我需要编写一个程序,输入6位二进制数后输出对应的十进制数,但无法将输入的二进制位与对应的2的幂列表匹配。例如输入100001时,应获取2的幂列表中的第一个元素32和最后一个元素1,再求和得到结果。

原代码

powersof2 = [32, 16, 8, 4, 2, 1]
e = []

i = str(input("Enter: "))
for a in powersof2:
    for x in i:
        if "0" in x:
            continue

        if "1" in x:
            e.append(a)
print(e)

目前代码会输出整个2的幂列表,问题出在嵌套循环逻辑:外层每遍历一个2的幂元素,内层就扫一遍所有二进制位,只要输入里存在"1",当前的2的幂就会被加入列表,最终所有元素都被添加进去。

修正方案

核心是让二进制位和2的幂列表的元素一一对应遍历,只有对应位置的二进制位是"1"时,才把对应的2的幂加入列表。

方法1:用zip同步遍历

powersof2 = [32, 16, 8, 4, 2, 1]
selected_powers = []

binary_str = str(input("Enter a 6-bit binary number: "))
# 同步配对二进制位与对应的2的幂
for bit, power in zip(binary_str, powersof2):
    if bit == "1":
        selected_powers.append(power)

print("选中的2的幂元素:", selected_powers)
print("对应的十进制数:", sum(selected_powers))

方法2:用索引遍历

powersof2 = [32, 16, 8, 4, 2, 1]
selected_powers = []

binary_str = str(input("Enter a 6-bit binary number: "))
# 通过索引绑定二进制位和2的幂的位置
for idx in range(len(binary_str)):
    if binary_str[idx] == "1":
        selected_powers.append(powersof2[idx])

print("选中的2的幂元素:", selected_powers)
print("对应的十进制数:", sum(selected_powers))

额外优化:直接累加结果

如果不需要保留选中的2的幂列表,可以直接计算十进制结果,省去列表存储步骤:

powersof2 = [32, 16, 8, 4, 2, 1]
decimal = 0

binary_str = str(input("Enter a 6-bit binary number: "))
for bit, power in zip(binary_str, powersof2):
    if bit == "1":
        decimal += power

print("十进制结果:", decimal)

内容的提问来源于stack exchange,提问作者Stonedpanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:35:49