How to generate all the binary options of N bits in JavaScript

1 Answer

0 votes
function generateAllBinaryOptions(N) {
    let binary = [];

    const total_bits = parseInt("1".repeat(N), 2) + 1;

    for (let i = 0; i < total_bits; i++) {
        binary.push(i.toString(2).padStart(N, '0'));
  	}

  return binary;
}


const N = 4;
console.log(generateAllBinaryOptions(N));




/*
run:

["0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"]

*/

 



answered Aug 26, 2023 by avibootz

Related questions

1 answer 118 views
1 answer 108 views
1 answer 113 views
1 answer 101 views
1 answer 111 views
1 answer 119 views
...