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:
- I am not allowed to use modulo, division, powers, or any libraries
that might help me to accomplish my goal. - I can use multiplication, addition, subtraction as well as comparisons.
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.
-
doesn't work. What does that mean, specifically?AMC– AMC2020年04月29日 02:27:28 +00:00Commented Apr 29, 2020 at 2:27
-
I don't get the output wantedMM1– MM12020年04月29日 09:40:53 +00:00Commented Apr 29, 2020 at 9:40
1 Answer 1
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
Sign up to request clarification or add additional context in comments.
Comments
lang-py