Problem

Converting decimal numbers to binary numbers can be done recursively. Write a function tha...

Converting decimal numbers to binary numbers can be done recursively. Write a function that takes a positive int argument and returns the corresponding binary number as an int composed of only 1s and 0s. For example, convert(5) returns the int: 101.

The insight for this problem comes from the fact that the rightmost digit of a decimal n is easy to calculate. It is the remainder when dividing by the base 2: n%2. To get the next rightmost digit, you take the resulting quotient, i.e., n2 = n/2, and find its remainder, n2%2, which is the next digit. Unfortunately, that generates the digits from right to left, and we want them from left to right. We could easily do that nonrecursively using string concatenation or string reversal, but in this exercise you are to use recursion to recursively calculate the digits. Effectively, you are letting recursion reverse the ordering: think in terms of calculating the rightmost digit as described previously, but then let recursion reverse the digits.

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
Solutions For Problems in Chapter 16
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT