Project 95: Decimal to Binary
Binary is as easy as "1, 10, 111"
Difficulty Level: High
Converting from Decimal to Binary
Example 1: 50 base 10 to base 2
Think about the powers of 2: 1, 2, 4, 8, 16, 32, 64, 128, 256,…
The highest power of 2 that is less than or equal to 50 is 2^5 = 32
To decompose 50 into sum of powers of 2, we need a 32 (2^5). This would leave 18 (50 -32).
The highest power of 2 that is less than or equal to 18 is 2^4 = 16. This would leave 2 (50 – 32 – 16).
The highest power of 2 that is less than or equal to 2 is 2^1 = 2. This would leave 0.
50 = 1*2^5 + 1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 0*2^0.
50 base 10 can be written as follows in binary: 110010
Example 2: 47 base 10 to base 2
Think about the powers of 2: 1, 2, 4, 8, 16, 32, 64, 128, 256,…
The highest power of 2 that is less than or equal to 47 is 2^5 = 32
To decompose 50 into sum of powers of 2, we need a 32 (2^5). This would leave 15 (47 -32).
The highest power of 2 that is less than or equal to 15 is 2^3 = 8. This would leave 7 (47 – 32 – 8).
The highest power of 2 that is less than or equal to 7 is 2^2 = 4. This would leave 3. (47 – 32 – 8 – 4)
The highest power of 2 that is less than or equal to 3 is 2^1 = 2. This would leave 1. (47 – 32 – 8 – 4 - 2)
The highest power of 2 that is less than or equal to 1 is 2^0 = 1. This would leave 0.
47= 1*2^5 + 0*2^4 + 1*2^3 + 1*2^2 + 1*2^1 + 1*2^0.
47 base 10 can be written as follows in binary: 101111
Project 95: Variable 'decimal' has been initialized. A working method called intDivision is available.
decimal is a positive integer between 5 and 250.
intDivision(x,y) returns how many times y can go into x.
intDivision(15,5) returns 3
intDivision(19,5) returns 3
Task: Appropriately assign the value of an array called 'bi' that represents the binary equivalent of 'decimal'.
Example: if decimal = 47, bi should be [1,0,1,1,1,1] (as explained above)
Example: if decimal = 50, bi should be [1,1,0,0,1,0] (as explained above).
Note: You can assume that 'bi' has already been assigned as an empty array (Javascript) or an empty ArrayList (Java)
**If your code works for 5 test cases, you can enter your e-mail address
Universal Computational Math Methods:
pow(5,2) returns 25.0
abs(-3.0) returns 3
sqrt(49.0) returns 7.0