The Binary Converter
MediumAcc. 92.4%
+30 XP 12
0s and 1s
Computers think in binary. To convert a decimal number to binary, you repeatedly divide by 2 and track the remainders in reverse order.
The Assignment
Your function receives a parameter named decimal.
- Initialize an empty string
binaryto store the result. - If
decimalis 0, print "0". - Use a
whileloop that continues as long asdecimalis greater than 0. - In each step:
- Calculate the remainder (
decimal % 2). - Add the remainder to the front of your
binarystring. - Update
decimalby dividing by 2 and rounding down (Math.floor).
- Calculate the remainder (
- After the loop, print the
binarystring.
01EXAMPLE 1
Input
decimal = 10Output
1010Explanation: 10 -> 5(0) -> 2(1) -> 1(0) -> 0(1) => 1010
Constraints
- Do not use toString(2).
- Use a loop to perform the conversion.
MathLoopsBinary
JavaScriptSystem handles I/O — write your function only
Loading...
3 Hidden
Input Arguments
decimal10
Expected Output
1010
Click RUN to test your solution