Ask Question
3 December, 08:24

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:

+2
Answers (1)
  1. 3 December, 09:23
    0
    The solution is written in Python

    binary = "" decimal = 13 quotient = int (decimal / 2) remainder = decimal % 2 binary = str (remainder) + binary while (quotient >0) : decimal = int (decimal / 2) quotient = int (decimal / 2) remainder = decimal % 2 binary = str (remainder) + binary print (binary)

    Explanation:

    Firstly, we declare a variable binary and initialize it with an empty string (Line 1). This binary is to hold the binary string.

    Next, we declare variable decimal, quotient and remainder (Line 2-4). We assign a test value 13 to decimal variable and then get the first quotient by dividing decimal with 2 (Line 3). Then we get the remainder by using modulus operator, % (Line 4). The first remainder will be the first digit joined with the binary string (Line 5).

    We need to repeat the process from Line 3-5 to get the following binary digits. Therefore create a while loop (Line 7) and set a condition that if quotient is bigger than 0 we keep dividing decimal by 2 and calculate the quotient and remainder and use the remainder as a binary digit and join it with binary string from the front (Line 9-11).

    At last, we print the binary to terminal (Line 13).
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “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 ...” in 📘 Engineering if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers