102k views
0 votes
Binary is a base-2 number system instead of the decimal (base-10) system we are familiar with. Write a recursive function PrintInBinary(int num) that prints the binary representation for a given integer. For example, calling PrintInBinary(5) would print 101. Your function may assume the integer parameter is non-negative. The recursive insight for this problem is to realize you can identify the least significant binary digit by using the modulus operator with value 2. For example, given the integer 35, mod by 2 tells you that the last binary digit must be 1 (i.e. this number is odd), and division by 2 gives you the remaining portion of the integer (17). What 's the right way to handle the remaining portion

User Mark Amery
by
4.2k points

1 Answer

8 votes

Answer:

In C++:

int PrintInBinary(int num){

if (num == 0)

return 0;

else

return (num % 2 + 10 * PrintInBinary(num / 2));

}

Step-by-step explanation:

This defines the PrintInBinary function

int PrintInBinary(int num){

This returns 0 is num is 0 or num has been reduced to 0

if (num == 0)

return 0;

If otherwise, see below for further explanation

else

return (num % 2 + 10 * PrintInBinary(num / 2));

}

----------------------------------------------------------------------------------------

num % 2 + 10 * PrintInBinary(num / 2)

The above can be split into:

num % 2 and + 10 * PrintInBinary(num / 2)

Assume num is 35.

num % 2 = 1

10 * PrintInBinary(num / 2) => 10 * PrintInBinary(17)

17 will be passed to the function (recursively).

This process will continue until num is 0

User Leusrox
by
4.9k points