|
| 1 | +<h1>Ones and Zeros <sup><sup>7 Kyu</sup></sup></h1> |
| 2 | + |
| 3 | +<sup> |
| 4 | + <a href="https://www.codewars.com/kata/578553c3a1b8d5c40300037c"> |
| 5 | + <strong>LINK TO THE KATA</strong> |
| 6 | + </a> - <code>FUNDAMENTALS</code> <code>ARRAYS</code> |
| 7 | +</sup> |
| 8 | + |
| 9 | +## Description |
| 10 | + |
| 11 | +Given an array of ones and zeroes, convert the equivalent binary value to an integer. |
| 12 | + |
| 13 | +Eg: `[0, 0, 0, 1]` is treated as `0001` which is the binary representation of `1`. |
| 14 | + |
| 15 | +Examples: |
| 16 | + |
| 17 | +``` |
| 18 | +Testing: [0, 0, 0, 1] ==> 1 |
| 19 | +Testing: [0, 0, 1, 0] ==> 2 |
| 20 | +Testing: [0, 1, 0, 1] ==> 5 |
| 21 | +Testing: [1, 0, 0, 1] ==> 9 |
| 22 | +Testing: [0, 0, 1, 0] ==> 2 |
| 23 | +Testing: [0, 1, 1, 0] ==> 6 |
| 24 | +Testing: [1, 1, 1, 1] ==> 15 |
| 25 | +Testing: [1, 0, 1, 1] ==> 11 |
| 26 | +``` |
| 27 | + |
| 28 | +However, the arrays can have varying lengths, not just limited to `4`. |
| 29 | + |
| 30 | +## Solutions |
| 31 | + |
| 32 | +```javascript |
| 33 | +const binaryArrayToNumber = arr => arr.reduce((acc, cur) => acc * 2 + cur, 0) |
| 34 | +``` |
| 35 | + |
| 36 | +```javascript |
| 37 | +const binaryArrayToNumber = arr => parseInt(arr.join(''), 2) |
| 38 | +``` |
0 commit comments