二进制到十进制使用递归,python

时间:2014-10-10 00:17:58

标签: python recursion binary decimal

需要帮助使用递归将二进制转换为十进制。

到目前为止,我有:

(2 * int(s [0]))+ int(s [1])

有s == 0和s == 1时的基本情况。

我不确定如何以递归方式传递此函数,以便函数将通过输入中的所有1和0来传递。

2 个答案:

答案 0 :(得分:0)

基本思路是选择字符串的最后一个字符并将其转换为数字,然后乘以适当的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上升到零的幂。换句话说,它要么总计加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,你可以看出为什么会这样。

答案 1 :(得分:0)

def IntegerConvert(num, base):
    if num == 0:
        return 0
    else:
        IntegerConvert.sum += pow(10, IntegerConvert.counter)*(num % base)
        IntegerConvert.counter += 1
        IntegerConvert(num/base, base)
    return IntegerConvert.sum
IntegerConvert.counter = 0
IntegerConvert.sum = 0
print IntegerConvert(10, 2)