109k views
1 vote
g Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:

1 Answer

4 votes

Final answer:

To convert a positive integer to a binary string, we divide the number by 2 and keep track of the remainders until the number is 0. The sequence of remainders forms the binary representation when read in reverse.

Step-by-step explanation:

The task is to write a program that converts a positive integer into binary. To achieve this, we can utilize the concept of dividing the number by 2 and keeping track of the remainder. This process will be repeated until the number becomes 0. The remainders, which will be 0's and 1's, form the binary representation of the integer when read in reverse order.

Example Python Program

Here is an example of a Python program that accomplishes the conversion:

def int_to_binary(n):
if n == 0:
return '0'
binary_digits = []
while n > 0:
remainder = n % 2
binary_digits.insert(0, str(remainder))
n = n // 2
return ''.join(binary_digits)

# User input
decimal_number = int(input("Enter a positive integer: "))
print("Binary representation:", int_to_binary(decimal_number))
User Mark Proctor
by
3.8k points