Closed kedarmhaswade closed 1 month ago
As discussed today, you should write two functions that test each other out:
decimal_to_binary(n)
: applies to an integer, n
, and returns a list that contains its binary representation.: applies to a list of digits (each digit being either a
0or a
1) and returns its decimal representation (the number like
348` directly, not a list of "decimal digits" although that is quite possible).When returning the binary representation as a list of 0
s and 1
s, you must specify the place value system of choice.
You have at least two choices:
Pay attention to the specifications.
Testing your code will become easier when you have these two complementary functions.
As you know, we use the decimal place-value system to represent numbers. We write the number three hundred and forty-eight as
348
in decimal representation: write the most significant digit (MSD,3
in this case) first and then write the subsequent digits from left to right.But
348
is just a representation of an abstract number using the integer powers of the number 10.It is clear that 348 = 3 102 + 4 101 + 8 * 100.
To represent a given number, we can use increasing powers (0, 1, 2, ...) of any number other than 1 (called the base). Perhaps you are familiar with James Tanton's exploding dots (using the n-to-1 machine).
Implement a function that when applied to a decimal integer,
n
, returns its representation in base2
(the so-called binary representation). As you might have correctly guessed, the binary representation of a number only consists of the digits0
and1
.Note that the function returns a binary representation. What value will the function return?
Take for example a number (decimal)
9
. You know that its binary representation is1001
. In what form will the function return this representation?How will you automatically test your function?