如何使用递归方式将二进制转换为十进制? [英] How could I convert Binary into Decimal using recursive way?
问题描述
我基本上完成了一切..我只是找不到将每个整数乘以 2^0、2^1 ... 等等的方法这是我的代码
I basically finished everything.. I just can't find a way to multiply each integer by 2^0, 2^1 ... and so on Here is my code
def BinaryToDecimal(binaryString):
if len(binaryString) == 0:
return 0
else:
return int(binaryString[-1:])*(2**(4-len(binaryString))) + BinaryToDecimal(binaryString[:len(binaryString)-1])
如果我输入了'1000',我会返回字符串的最后一位数字并通过消除最后一位数字来进行递归,'1000' --> '100' --> '10' 等等
If I have input '1000', I return last digit of the string and do recursion by eliminating the last digit so, '1000' --> '100' --> '10' and so on
这里的问题是我找不到一种方法来将最后一位数字乘以其相应的 2 次幂.当二进制字符串的长度为 4,3,2 时,如何得到 0,1,2,3 的任何想法,1 ?
The problem here is that I just cannot find a way to multiply last digit by its corresponding power of 2. Any thought of how to get 0,1,2,3 when length of binary string is 4,3,2,1 ?
推荐答案
您使这变得比需要的更复杂.无需功率计算.
You're making this more complicated than it needs to be. No power calculation is required.
def binary_to_decimal(bstring):
if not bstring:
return 0
return binary_to_decimal(bstring[:-1]) * 2 + int(bstring[-1])
# Test
for i in range(16):
b = format(i, 'b')
n = binary_to_decimal(b)
print('{:2} {:4} -> {}'.format(i, b, n))
输出
0 0 -> 0
1 1 -> 1
2 10 -> 2
3 11 -> 3
4 100 -> 4
5 101 -> 5
6 110 -> 6
7 111 -> 7
8 1000 -> 8
9 1001 -> 9
10 1010 -> 10
11 1011 -> 11
12 1100 -> 12
13 1101 -> 13
14 1110 -> 14
15 1111 -> 15
这个函数也能正确处理前导零:
This function also handles leading zeros correctly:
for i in range(16):
b = format(i, '05b')
n = binary_to_decimal(b)
print('{:2} {} -> {}'.format(i, b, n))
输出
0 00000 -> 0
1 00001 -> 1
2 00010 -> 2
3 00011 -> 3
4 00100 -> 4
5 00101 -> 5
6 00110 -> 6
7 00111 -> 7
8 01000 -> 8
9 01001 -> 9
10 01010 -> 10
11 01011 -> 11
12 01100 -> 12
13 01101 -> 13
14 01110 -> 14
15 01111 -> 15
<小时>
实际上,我们甚至不需要那个 int
调用,如果我们假设我们只传递有效字符串:
Actually, we don't even need that int
call, if we assume we only get passed valid strings:
def binary_to_decimal(bstring):
if not bstring:
return 0
return binary_to_decimal(bstring[:-1]) * 2 + (bstring[-1] == '1')
这篇关于如何使用递归方式将二进制转换为十进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!