6.7k views
5 votes
Write a program that takes in a positive integer as input, and outputs a string of 1's and O's representing the integer in binary. For an integer x, the algorithm is:

As long as x is greater than 0
Output x&2 (remainder is either 0 or 1 )
x=x/2

Note: The above algorithm outputs the 0's and 1's in reverse order. You will need to write a second function to reverse the string.

Ex: If the input is:
6

the output is:
110

The program must define and call the following two functions. Define a function named IntToReverseBinary0 that takes an int as a parameter and returns a string of 1's and 0's representing the integer in binary (in reverse). Define a function named StringReverse0 that takes a string as a parameter and returns a string representing the input string in reverse.

string IntToReverseBinary(int integervalue) string
StringReverse(string userString)

1 Answer

5 votes

To write a program that converts a positive integer into a binary string, we can use the given algorithm.

Next, we need to define a function called "StringReverse" that takes a string as a parameter and returns the input string in reverse order.

Here's an example implementation in Python:

def IntToReverseBinary(integervalue):

binary_string = ""

while integer value > 0:

remainder = integer value & 1

binary_string += str(remainder)

integer value = integer value // 2

return binary_string

def StringReverse(userString):

return userString[::-1]

# Main program

input_number = int(input("Enter a positive integer: "))

binary_string = IntToReverseBinary(input_number)

reversed_binary_string = StringReverse(binary_string)

print(reversed_binary_string)

```

When the user enters 6, the program will output "011" because the binary representation of 6 is "110" in reverse.

User Comendeiro
by
8.1k points