Decimal to Binary (INTRN004) : Solution with hints


Hint 1:

Click to view

To go from binary to decimal, we use the following procedure.

We start with res = 0.
we take the right-most digit, and multiply by 1, and add to res.

Then we take second-right most digit, and multiply by 2, and add to res.


We take i^{\texttt{th}} from the right, and multiply it by 2^{i - 1} and add res.

We want to reverse this process.

Try writing the number 5 in binary.

Hint 2:

Click to view

When we take N \bmod 2, we get the remainder when N is divided by 2.

What happens when we divide N by 2 (integer division)?

Write 9 in binary, then divide it by 2, and write the result in binary.
Then divide that number by 2, and write the result in binary.

Hint 3:

Click to view

Dividing by 2 chops off the right-most digit in the binary representation.

Hint 4:

Click to view

How long do we need to do this process to get all the digits in the binary representation of N?

Hint 5:

Click to view

Keep dividing by 2 until you reach 0.

Hint 6:

Click to view

In what order do we get the binary digits via this process?
Try with examples 9 and 8.

Hint 7:

Click to view

Reverse order.

Hint 8:

Click to view

We can store the individual binary digits in a list and print it in reverse order.