2014-10-10 44 views
0

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

到目前为止,我有:

(2 * INT(S [0]))+ INT(S [1])

用碱的情况下为当s == 0和s == 1 。

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

+0

首先,s == 0和s == 1不可能是真的,因为's'显然是一个序列。你的意思是'len(s)== 0'和'len(s)== 1'也许?或者有些不同? – abarnert 2014-10-10 00:35:13

+0

二,你了解递归的基本概念吗?你至少能写出一个处理基本情况的函数,有猜测,或者只是一个'#帮我用这个部分'来处理剩余的情况? – abarnert 2014-10-10 00:35:51

回答

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,你就会明白为什么这个工程。

+0

我想通过这样的 问题的工作,让我们们的说法= 1010 '101 + 0 10 + 1 1 + 0 那么它会像这样: (2 * 1)+ 0 = 2 (2 * 2)+ 1 = 5 (5 * 2)+ 0 = 10 最终答案返回将是10 到目前为止我想出这个论坛: 如果s ==” 0': return 0 elif s =='1': return 1 else: if(len(s))> 1:(n) rest =(2 * n)+(int(s [-1:])) ) print(rest)' 并且这适用于s ='100'或s ='111',但不会更高 – user4127524 2014-10-10 01:42:04

+0

@ user4127524您可以将该代码放在http://pastebin.com上,因此更容易我阅读? – royhowie 2014-10-10 01:46:36

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) 
相关问题