6.23 LAB: Convert to binary - functions Instructor note: This is a lab from a previous chapter that now requires the use of a function. If you weren't able to solve it before, think of this as a new opportunity. 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 the output is: 110 Your 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)

Respuesta :

Answer:

The program in Python is as follows:

import math

def integer_to_reverse_binary(integer_value):

   remainder = ""

   while integer_value>=1:

       remainder+=str(integer_value % 2)

       integer_value=math.floor(integer_value/2)

   reverse_string(remainder)

def reverse_string(input_string):

   binaryOutput=""

   for i in range(len(input_string)-1,-1,-1):

       binaryOutput = binaryOutput + input_string[i]

   print(binaryOutput)

integer_value = int(input("Enter a Number : "))

integer_to_reverse_binary(integer_value)

Explanation:

This imports the math module

import math

This defines the integer_to_reverse_binary function

def integer_to_reverse_binary(integer_value):

This initializes the remainder to an empty string

   remainder = ""

This loop is repeated while the integer input is greater than or equal to 1

   while integer_value>=1:

This calculates the remainder after the integer value is divided by 2

       remainder+=str(integer_value % 2)

This gets the floor division of the integer input by 2

       integer_value=math.floor(integer_value/2)

This passes the remainder to the reverse_string function

   reverse_string(remainder)

The reverse_string function begins here

def reverse_string(input_string):

This initializes the binaryOutput to an empty string

   binaryOutput=""

This iterates through the input string i.e. the string of the remainders

   for i in range(len(input_string)-1,-1,-1):

This reverses the input string

       binaryOutput = binaryOutput + input_string[i]

This prints the binary output

   print(binaryOutput)

The main begins here

This gets input for integer_value

integer_value = int(input("Enter a Number : "))

This passes the integer value to the integer_to_reverse_binary function

integer_to_reverse_binary(integer_value)

ACCESS MORE