I can't wrap my head around how this simple recursive function works:
void printBinary(const int& n)
{
if(n < 2)
{
cout << n;
}
else
{
printBinary(n / 2);
printBinary(n % 2);
}
}
I know it has something to do with n / 2 "chopping" off the last digit of the binary representation and n % 2 yielding such last digit of the binary representation, but when I recursively trace this code it just seems like magic. I can't come up with a simple logical explanation.
Edit: This is a great explanation of the algorithm, and leads me to kind of rephrase my question to: why does n % 2, or the remainder of a decimal number, give you the binary digits of such number. What is the logic behind that?
n % 10gives you the last base-10 digit? Thenn % 2is the same in base 2.a0 + 2*a1 + 4*a2 + 8*a3 + ...where a0,a1,... are the binary digits from right to left. If you work out the quotient and remainder by 2, you'll geta1 + 2*a2 + 4*a3 + ...anda0respectively.