Python | Print Binary Equivalent of a Number without Using Recursion

In the previous article, we saw the same problem but there we solved using recursion. Here we will go through all the methods in which there is no concept of recursion. So let us start with the coding part.

Method 1: Using a bin function and replace() function

def convertToBinary(n):
    print(bin(n).replace("0b", ""))
   
num = int(input("Enter the number whose binary you want:"))

convertToBinary(num)

Explanation

In this method, we used the bin() function. The main functionality of this function is to return the binary number. The binary representation of a given number is returned by the bin() function. The prefix 0b will always appear before the result. Now to remove the prefix, we used the replace() function of the Python

Method 2: Using a bin function and string slicing

def convertToBinary(n):
    print(bin(n)[2:])
   
num = int(input("ENter the number whose binary you want:"))

convertToBinary(num)

Explanation:

Here we replaced the replace() function with [2:]. This is the concept of string slicing wherein we mean that cut the part of the string from the second position.

Method 3: Using a format() function

def convertToBinary(n):
    bin_num = format(int(n), 'b')
    print(bin_num)
   
   
num = int(input("ENter the number whose binary you want:"))

convertToBinary(num)

Explanation:

Here we used the format function. A formatted version of a value defined by the format specifier is returned by the format() function. and the other argument “b” is used to represent the string as a byte string.

Method 4: With the help of the shift operator

def convertToBinary(n):
    ans = ""
    if ( n == 0 ):
        return 0
    while ( n ):
        ans += str(n&1)
        n = n >> 1
     
    ans = ans[::-1]
    print(ans)
   
num = int(input("Enter the number whose binary you want:"))

convertToBinary(num)

Explanation:

In this very last method, which is quite long, we made use of the operators that Python offers. At first, we checked for the number equal to 0, if that is the case then simply return o. If not then we used a while loop, inside that we used the AND operator between n and 1 and converted the input to an integer, and added the value to and(empty in the first iteration). Lastly, we used the left shift operator. The bitwise left shift operator in Python moves the left operand bits a specified number of times to the left in the right operand. Simply said, 0s are added to the end of the binary integer.

Here is the end to our 4 methods to solve the given problem.

Share:

Author: Ayush Purawr