gpt4 book ai didi

python - 断言一个数字是二进制的

转载 作者:行者123 更新时间:2023-12-05 09:03:58 25 4
gpt4 key购买 nike

我正在做作业,遇到了一个问题。我不得不将二进制数字串接起来。假设我们加入了 (1, 3) - 1 是起始数字,3 表示我将使用另外 2 个数字(如果我加入了 (5, 4),id 将使用 5、6、7 和 8)1 12 103 11结果 11011

def num_to_2(number):
num2 = 0
exp = 0
while number >= 1:
num2 += (number % 2) * (10 ** exp)
number = number // 2
exp += 1
return num2


def num_lenght(number):
if number == 0:
return 0
lenght = 0
while number >= 1:
number /= 10
lenght += 1
return lenght


def joined(start, count):
result = 0
end = start + count - 1
for i in range(end, start - 1, -1):
number = num_to_2(i)
res_lenght = num_lenght(result)
result += number * (10 ** res_lenght)
return result


def main():
assert joined(1, 3) == 0b11011
assert joined(10, 4) == 0b1010101111001101
assert joined(8, 5) == 0b10001001101010111100
assert joined(99, 2) == 0b11000111100100
assert joined(999, 3) == 0b111110011111111010001111101001
assert joined(1111, 1) == 0b10001010111

函数正常工作,但它给我的结果没有 0b 前缀,我需要它来传递断言。我如何在那里添加它?还有:我不能使用字符串。

提前致谢!

编辑:我添加了其余的代码,这样更有意义

最佳答案

我已经解决了我的问题,我所要做的就是“手动”将伪二进制数转换为以 10 为基数的数字。这是我的代码:

def convert_to_2(number):
num2 = 0
exp = 0
while number >= 1:
num2 += (number % 2) * (10 ** exp)
number = number // 2
exp += 1
return num2


def num_lenght(number):
if number == 0:
return 0
lenght = 0
while number >= 1:
number /= 10
lenght += 1
return lenght


def joined(start, count):
result = 0
end = start + count - 1
for i in range(end, start - 1, -1):
number = convert_to_2(i)
res_lenght = num_lenght(result)
result += number * (10 ** res_lenght)
result = convert_to_10(result)
return result


def convert_to_10(number):
num10 = 0
exp = 0
while number >= 1:
num10 += (number % 10) * (2 ** exp)
number = number // 10
exp += 1
return num10


def main():
assert joined(1, 3) == 0b11011
assert joined(10, 4) == 0b1010101111001101
assert joined(8, 5) == 0b10001001101010111100
assert joined(99, 2) == 0b11000111100100
assert joined(999, 3) == 0b111110011111111010001111101001
assert joined(1111, 1) == 0b10001010111


if __name__ == "__main__":
main()

非常感谢你的帮助(:

关于python - 断言一个数字是二进制的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69326189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com