Back to Freecodecamp

Challenge 52: Binary to Decimal

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

latest1.3 KB
Original Source

--description--

Given a string representing a binary number, return its decimal equivalent as a number.

A binary number uses only the digits 0 and 1 to represent any number. To convert binary to decimal, multiply each digit by a power of 2 and add them together. Start by multiplying the rightmost digit by 2^0, the next digit to the left by 2^1, and so on. Once all digits have been multiplied by a power of 2, add the result together.

For example, the binary number 101 equals 5 in decimal because:

mathml
1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 4 + 0 + 1 = 5

--hints--

toDecimal("101") should return 5.

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

toDecimal("1010") should return 10.

js
assert.equal(toDecimal("1010"), 10);

toDecimal("10010") should return 18.

js
assert.equal(toDecimal("10010"), 18);

toDecimal("1010101") should return 85.

js
assert.equal(toDecimal("1010101"), 85);

--seed--

--seed-contents--

js
function toDecimal(binary) {

  return binary;
}

--solutions--

js
function toDecimal(binary) {
  let decimal = 0;
  for (let i = 0; i < binary.length; i++) {
    const bit = parseInt(binary[binary.length - 1 - i], 10);
    decimal += bit * Math.pow(2, i);
  }
  return decimal;
}