Question: This is scala programming A (5 points) Recursively compute binary representation Given a positive integer n, we wish to compute its binary representation as a
This is scala programming
A (5 points) Recursively compute binary representation
Given a positive integer n, we wish to compute its binary representation as a string.
- Use of var and loops forbidden.
- Inbuilt functions that directly perform conversion are also forbidden.
Example: if input is 5, output should be "101".
Use the following scheme:
- If number is 0 or 1, we can convert them into binary string "0" or "1", respectively.
- If input number n is odd, recursively convert (n-1)/2 into binary and append a 1 to the end of the string returned.
- else (input number n is even) convert n/2 into binary and append 0 to end of the string returned.
def convertToBinary(n: Int): String = { require( n >= 0) // If this is violated, you will get a "requirement failed message" // YOUR CODE HERE ??? }
//BEGIN TEST assert(convertToBinary(1) == "1", "(1)decimal must be 1 binary") assert(convertToBinary(5) == "101", "5 must be 101 binary") assert(convertToBinary(11) == "1011", "(11) must be 1011") assert(convertToBinary(4100) == "1000000000100", "(4100) must be 1000000000100") assert(convertToBinary(30108100) == "1110010110110100111000100", "(30108100) must be 1110010110110100111000100") passed(5) //END TEST

B (5 points) Tail Recursive convertToBinary Now, write a tail recursive version of the convertToBinary function, called convertToBinaryTail. You should implement the helper function as a tail recursive function. Use of var and loops forbidden. Inbuilt functions that directly perform conversion are also forbidden. [ ]: import scala.annotation.tailrec @tailrec final def convertToBinaryHelper (n: Int, stringSoFar: String): String = { require(n >= 1) // YOUR CODE HERE ??? } def convertToBinaryTail(n: Int): String = { // YOUR CODE HERE ??? } [ ]: // BEGIN TEST assert(convertToBinaryTail(1) == "1", "(1) decimal must be 1 binary") assert (convertToBinaryTail(5) == "101", "5 must be 101 binary") et (convertToBinaryTail(11) == "1011", "(11) must be 1011") assert(convertToBinaryTail(4100) == "1000000000100", "(4100) must be 1000000000100") assert (convertToBinaryTail(30108100) == "1110010110110100111000100", "(30108100) must be 1110010110110100111000100") passed (5) //END TEST
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
