基本思想是取出字符串的最后一个字符并将其转换为数字,然后将其乘以 2 的适当幂。我已经为您注释了代码。
# we need to keep track of the current string,
# the power of two, and the total (decimal)
def placeToInt (str, pow, total):
# if the length of the string is one,
# we won't call the function anymore
if (len(str) == 1):
# return the number, 0 or 1, in the string
# times 2 raised to the current power,
# plus the already accumulated total
return int(str) * (2 ** pow) + total
else:
# grab the last digit, a 0 or 1
num = int(str[-1:])
# the representation in binary is 2 raised to the given power,
# times the number (0 or 1)
# add this to the total
total += (num * (2 ** pow))
# return, since the string has more digits
return placeToInt(str[:-1], pow + 1, total)
# test case
# appropriately returns 21
print(placeToInt("10101", 0, 0))
现在,让我们手动检查一下,这样你就明白为什么会这样了。
# n = 101 (in binary
# this can also be represented as 1*(2^2) + 0*(2^1) + 1*(2^0)
# alternatively, since there are three digits in this binary number
# 1*(2^(n-1)) + 0*(2^(n-2)) + 1*(2^(n-3))
那么这是什么意思?嗯,最右边的数字是 1 或 0 乘以 2 的 0 次方。换句话说,它要么给总数加 1,要么加 0。最右边的第二个数字呢?它在总数中增加 0 或 2。下一个? 0 或 4。看到模式了吗?
让我们编写伪代码:
let n = input, in binary
total = 0
power of 2 = 0
while n has a length:
lastDigit = last digit of n
add (2^pow)*lastDigit to the current total
由于我们从一个幂和总为 0 开始,您可以看到为什么会这样。