2014-10-10 47 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) 
相關問題