我的任务是在Two's Compliment系统中编写一个带有任意长度二进制字符串的函数,并返回基数为10的相应整数。我不能使用for或while循环,我不能使用内置在转换功能。我可以使用递归。
我编写了一个辅助函数,它接受二进制字符串中的第一个数字,并找到基数为10的值,这将添加到总和中,我已将其复制到下面。
def first(str):
'''this program finds the value in base 10 of the 0th digit in a string of binary'''
n=len(str)
return int(str[0])*(2**(n-1))
我需要处理负数的帮助,以及整体功能的格式化。 谢谢!
答案 0 :(得分:0)
def bin(s):
return 0 if not s else 2*bin(s[:-1]) + int(s[-1])
convert_2_to_decimal = lambda s: bin(s[1:]) - int(s[0])*2**(len(s)-1)