-1

I need to write a function that converts an integer into binary. The function definition I have written so far is:

def decimalToBinary(number):
    if number > 1:
        decimalToBinary(number//2)
    print(number % 2, end = '')

My problem is that:

  1. I should return the result instead of printing it, and I am unsure how to do that.
  2. I am overall unsure if my code is the best recursive code I could have written.

Thank you for your time!

pythonoob
  • 13
  • 4
  • 1
    Does this answer your question? [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – Reti43 Mar 10 '21 at 18:15

2 Answers2

1

Convert the digit to a string, and use return instead of print. Then concatenate it with the recursive call.

def decimalToBinary(number):
    if number > 1:
        return decimalToBinary(number//2) + str(number % 2)
    else:
        return str(number % 2)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can pass a count variable to position the digits

def decimalToBinary(number, count = 0):
    if number > 1:
        return ((number%2) * (10**count) + decimalToBinary(number//2, count+1))
    return ((number%2) * (10**count))

Also, if you need a non-recursive function you can use something like this

def LinealDecimalToBinary(num):
    count = 0
    binNum = 0
    while(num > 0):
        binNum += (num%2) * (10**count)
        num = num//2
        count += 1
    return binNum