Back to Freecodecamp

Challenge 53: Decimal to Binary

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da675.md

latest1.2 KB
Original Source

--description--

Given a non-negative integer, return its binary representation as a string.

A binary number uses only the digits 0 and 1 to represent any number. To convert a decimal number to binary, repeatedly divide the number by 2 and record the remainder. Repeat until the number is zero. Read the remainders last recorded to first. For example, to convert 12 to binary:

mathml
12 ÷ 2 = 6 remainder 0
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1

12 in binary is 1100.

--hints--

toBinary(5) should return "101".

js
assert.equal(toBinary(5), "101");

toBinary(12) should return "1100".

js
assert.equal(toBinary(12), "1100");

toBinary(50) should return "110010".

js
assert.equal(toBinary(50), "110010");

toBinary(99) should return "1100011".

js
assert.equal(toBinary(99), "1100011");

--seed--

--seed-contents--

js
function toBinary(decimal) {

  return decimal;
}

--solutions--

js
function toBinary(decimal) {
  if (decimal === 0) return "0";
  let binary = "";
  while (decimal > 0) {
    binary = (decimal % 2) + binary;
    decimal = Math.floor(decimal / 2);
  }
  return binary;
}