Computer Science, asked by anaghadevadas0084, 3 months ago

write a function python to print the binary equivalent of a passed positive integer​

Answers

Answered by anindyaadhikari13
2

Required Answer:-

Question:

  • Write a Python function to print binary equivalent of a passed positive number.

Solution:

Here comes the program.

1. Using inbuilt function.

def dec_to_bin(n):

b=bin(n).replace("0b"," ")

print("Binary Equivalent:",b)

n=int(input("Enter a number: "))

dec_to_bin(n)

2. Using loop.

def dec_to_bin(n):

s=""

while n>0:

s+=str(n%2)

n//=2

print(s[::-1])

n=int(input("Enter an integer: "))

print("Binary Equivalent:",end=" ")

dec_to_bin(n)

3. Using recursion.

def dec_to_bin(n):

if n>=1:

dec_to_bin(n//2)

print(n%2,end="")

n=int(input("Enter an integer: "))

print("Binary Equivalent:",end=" ")

dec_to_bin(n)

Algorithm:

  1. START
  2. Divide the number by 2.
  3. Find the quotient and remainder and store the values.
  4. Continue steps 2 and 3 till number is greater than 0.
  5. Display the result in reverse order.

Refer to the attachment for output ☑.

Attachments:
Similar questions