I'm trying to convert a decimal number in binary but I can't seem to understand why my code doesn't work. Before checking it I need to precise that:
That said, here is my code:
def binary_conv(n):
p1 = 1
p2 = 1
lst = list()
counter1 = 0
counter2 = 0
while p1 <= n:
p1 *=2
counter1 += 1
len_bin = counter1
lst = len_bin*[0]
counter1 -= 1
while n > 0:
p2 *= 2
counter2 += 1
if (p2*2) == p1:
lst[counter1-counter2] = 1
p1 = p2
p2 = 1
n = n-p1
counter2= 0
print(lst)
If you need more clarifications, don't hesitate to ask.
I actually found the answer, here it is for those interested:
def binary_conv(n):
p1 = 1
p2 = 1
lst = list()
counter1 = 0
counter2 = 0
while p1 <= n:
p1 *= 2
counter1 += 1
len_bin = counter1
lst = len_bin*[0]
counter1 -= 1
while n > 0:
p2 *= 2
counter2 += 1
if (p2 * 2) > n:
if n == 1:
lst[-1] = 1
break
lst[counter1 - counter2] = 1
p1 = p2
p2 = 1
n = n - p1
counter2 = 0
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments