Question: Problem 4 Converting decimal numbers to binary numbers can be done recursively. Write a function that takes a positive int argument and returns the corresponding
Problem
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 ones and zeros. For example, convert
returns the int:
The insight for this problem comes from the fact that the rightmost digit of a
decimal is easy to calculate. It is the remainder when dividing by the base :
To get the next rightmost digit, you take the resulting quotient, that is
and find its remainder, 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 recur sion 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
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
