163k views
16 votes
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)
Note: This is a lab from a previous chapter that now requires the use of a function.

1 Answer

7 votes

Answer:

#include <iostream>//header file

#include <string>//header file

using namespace std;

string integer_to_reverse_binary(int integer_value)//defining a method integer_to_reverse_binary

{

string ret = "";//defining string variable

while (integer_value > 0) //using while loop to check integer_value value is greater than 0

{

ret += '0' + (integer_value % 2);//adding zeros in remainder value

integer_value /= 2;//holding quotient value

}

return ret;//return string value

}

string reverse_string(string input_string)//defining a method reverse_string that holds a parameter user_String

{

string result;//defining a string variable

for (int i = 0; i < input_string.length(); ++i)//use for loop to calculate value

{

result += input_string[input_string.length()-i-1];//add value in result variable

}

return result;//result result variable value

}

int main()//defining main method

{

int num;//defining integer variable

string str;//defining string variable

cin >> num;//input num value

str = integer_to_reverse_binary(num);//use str variable to call the integer_to_reverse_binary method

cout << reverse_string(str) << endl;//printing the reverse_string method value

return 0;

}

Output:

6

110

Step-by-step explanation:

In this code two string method "integer_to_reverse_binary and reverse_string" is defined that holds one parameter "integer_value and input_string".

In the first method a string variable is defined, that use the while loop to check integer value is greater than 0 and add zeros in the value and return its value as a string.

In the second it reverse the string value and store into the result variable, and in the main method the "num and str" variable is defined, and in the num it takes integer value and pass into the above method and print its return value.

User Alhcr
by
4.6k points