【问题标题】:binary to decimal using recursion,python二进制到十进制使用递归,python
【发布时间】:2014-12-05 01:36:48
【问题描述】:

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

到目前为止我有:

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

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

我不知道如何递归地传递它,以便函数将传递输入中的所有 1 和 0。

【问题讨论】:

  • 首先,s==0s==1 不可能是真的,因为s 显然是一个序列。你的意思是len(s)==0len(s)==1 可能吗?还是有什么不同?
  • 二、你了解递归的基本概念吗?你至少可以写一个函数来处理基本情况,猜测或只是一个# help me with this part 剩下的情况?

标签: python recursion binary decimal


【解决方案1】:

基本思想是取出字符串的最后一个字符并将其转换为数字,然后将其乘以 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 开始,您可以看到为什么会这样。

【讨论】:

  • 我正在尝试解决这样的问题,假设 s=1010 101 + 0 10 + 1 1+0 it will then work like this: (2*1)+0= 2 (2*2)+1=5 (5*2)+0=10 the final answer returned would be 10. so far i've come up with this : if s=='0': return 0 elif s=='1': return 1 else: if (len(s))>1: n=(2*(int(s[0]))) + (int(s[1])) print(n) rest= (2*n) + (int(s[-1:])) print(rest) 这适用于 s='100' 或 s='111' 但不是更高
  • @user4127524 你能把那个代码放在pastebin.com上,这样我更容易阅读吗?
【解决方案2】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2016-05-03
    • 2022-11-14
    • 2017-01-26
    • 2021-07-09
    • 2016-01-17
    • 2014-04-18
    相关资源
    最近更新 更多