In: Computer Science
IN PYTHON
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:
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, Output is: 110
Program must define and call the following two functions. The
function integer_to_reverse_binary() should return a string of 1's
and 0's representing the integer in binary (in reverse). The
function reverse_string() should return a string representing the
input string in reverse.
def integer_to_reverse_binary(integer_value)
def reverse_string(input_string)
included in code...
''' insert code here'''
if __name__ == '__main__':
''' Inset code here...Your code must call the function. '''
I have written the code as required and also attached the sample input output.
Code:
def integer_to_reverse_binary(n):
reverse_binary=''
while n != 0:
reverse_binary+=str(n%2)
n=n>>1;
return reverse_binary
def reverse_string(reverse_binary):
binary=''
for i in reverse_binary:
binary=i+binary
return binary
if __name__ == '__main__':
number=int(input())
reverse_binary=integer_to_reverse_binary(number)
binary=reverse_string(reverse_binary)
print(binary)
Input: 14
Output:
ScreenShot of Code: