To find the representation of base 2, we look for bits b0...bn such that
n = bn * 2^n + b_(n - 1) * 2^(n - 1) + ... + b1 * 2^1 + b0 * 2^0
Now we will focus on finding b0, b1, ..., bn . note that
(bn * 2^n + b_(n - 1) * 2^(n - 1) + ... + b1 * 2^1 + b0 * 2^0) % 2 = b0
because b0 * 2^0 % 2 = b0 and bj * 2^j % 2 = 0 when j >= 1 with 2^j % 2 = 0 if j >= 1 . Thus,
n = bn * 2^n + b_(n - 1) * 2^(n - 1) + ... + b1 * 2^1 + b0 * 2^0 => n % 2 = (bn * 2^n + b_(n - 1) * 2^(n - 1) + ... + b1 * 2^1 + b0 * 2^0) % 2 = b0
we found that b0 = n % 2 . This key fact is number one .
Now divide by 2:
n / 2 = (bn * 2^n + b_(n - 1) * 2^(n - 1) + ... + b1 * 2^1 + b0 * 2^0) = bn * 2^(n - 1) + b_(n - 1) * 2^(n - 2) + ... + b1 * 2^1
Now let me stop here. Let's take a close look at the binary representation for n / 2 . Note that it is exactly equal to the binary representation of n with only the last beaten off. it
n = bn b_(n-1) ... b1 b0 n / 2 = b_n b_(n-1) ... b1
This is a key fact number two .
So, let's collect what we learned.
The binary representation of n is the binary representation of n / 2 with the last digit of the binary representation of n added. This is out of key fact number two .
The last digit of the binary representation of n can be calculated by computing n % 2 . This is from the key fact number one .
All this is true, except for one case: when n = 0 . In this case, the binary representation of n is 0 . If we try to use the rule of dividing by 2 , we will never stop dividing by 2. So, we need a rule that catches when n = 0 .
So, to compute the binary representation of n , first compute the binary representation of n / 2 , then add the result n % 2 , but be sure to handle the case where n = 0 . Let it be written that in the code:
// print binary representation of n void ToBin(int n) { if(n > 1) { // this is to handle zero! ToBin(n / 2); // this will print the binary representation of n } print(n % 2); // this will print the the last digit }