Question
(I need help programming this code. If you can do it in Scala, that would be great. If not, Python works too. Thank you.) Write
(I need help programming this code. If you can do it in Scala, that would be great. If not, Python works too. Thank you.)
Write a function convertToBinary that inputs a non-negative integer , and returns its binary representation as a String.
-Use of var and loops forbidden.
-Inbuilt functions that directly perform conversion are also forbidden.
-Try a recursive solution but no need to make it tail recursive for this part.
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.
For your convenience, we have provided an "iterative solution" that uses a while loop. But your solution must conform to the restrictions above.
Note: ??? indicates that there is a missing function or code fragment that needs to be filled in. In scala, it is also a macro that throws a NotImplemented exception. Make sure that you remove the ??? and replace it with the answer.
###CODE
def convertToBinaryLoop(n0: Int): String = { require(n0 >= 0) var n:Int = n0 var str = "" if (n == 0){ "0" } else { while (n > 0 ) { val bit = n % 2 str = bit.toString + str n = n/2 // This is integer division } str } }
Results:
defined function convertToBinaryLoop
println(s"0 in binary = ${convertToBinaryLoop(0)}") println(s"1 in binary = ${convertToBinaryLoop(1)}") println(s"5 in binary = ${convertToBinaryLoop(5)}") println(s"10 in binary = ${convertToBinaryLoop(10)}") println(s"12 in binary = ${convertToBinaryLoop(12)}") println(s"19 in binary = ${convertToBinaryLoop(19)}") println(s"29 in binary = ${convertToBinaryLoop(29)}") println(s"51 in binary = ${convertToBinaryLoop(51)}")
Results:
0 in binary = 0 1 in binary = 1 5 in binary = 101 10 in binary = 1010 12 in binary = 1100 19 in binary = 10011 29 in binary = 11101 51 in binary = 110011
// 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
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started