livepython.net

296. Python Program to Turn a Number into Binary by Hand

MediumPhase 2 · Practice

A few steps, and all of them use tools you know: a while loop, % and //, and joining text with +.

Overview

Computers store numbers in binary: a way to write numbers with only the digits 0 and 1. Turning a number into binary by hand is a classic loop exercise.

Problem Statement

Musa makes a poster about how computers store numbers. Read a whole number n and turn it into binary by hand:

  • Divide the number by 2, and keep the remainder. It is 0 or 1.
  • Go on with the whole-number result of the division, and divide it by 2 again.
  • Stop when the number is 0.
  • Read the remainders backwards, from the last one to the first. That is the binary number.

Do the steps yourself with % and //. Do not use bin() or format(): the point is to do it by hand. The number 0 is 0 in binary.

Print one line: 13 in binary is 1101, with your number and its binary form.

Examples

Example 1. Input 13 gives:

13 in binary is 1101

Why: 13 divided by 2 is 6, remainder 1. 6 gives 3, remainder 0. 3 gives 1, remainder 1. 1 gives 0, remainder 1. Read backwards, the remainders are 1101.

Example 2. Input 0 gives:

0 in binary is 0

Why: 0 has nothing to divide, so there are no remainders. Zero is written 0 in binary too.

Input

One whole number n, 0 or more. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line, as shown above. The binary number has no zeros in front. The tests try 8 different inputs.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 11 · While Loops
solution.py
# write your code here

EXPECTED OUTPUT

113 in binary is 1101

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.