Python | Print Binary Equivalent of an Integer using Recursion

In order to solve this problem, we only have one method to use. Let us take a look at it.

def convertToBinary(n):
   if n > 1:
       convertToBinary(n//2)
   print(n % 2,end = '')


num = int(input("Enter the number whose binary you want:"))

convertToBinary(num)

Output:

Enter the number whose binary you want:36
100100

Explanation:

Here we used the method of floor division (//). All that we did is divided the number that was passed to the function by 2 (only if the number is greater than 1). Floor division brings down the answer to the closest whole number digit. The output that we get is then passed to perform a modulo operation and finally, we printed out the output of that expression.

Here is the end, we will definitely come back with some more methods to solve this problem.

Share:

Author: Ayush Purawr