Function that converts a decimal to binary: how to return result instead of printing it?

Question:

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!

Asked By: pythonoob

||

Answers:

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)
Answered By: Barmar

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
Answered By: Alan Hernández