2

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.

2
  • doesn't work. What does that mean, specifically? Commented Apr 29, 2020 at 2:27
  • I don't get the output wanted Commented Apr 29, 2020 at 9:40

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.