-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEx.5.html
51 lines (44 loc) · 1.95 KB
/
Ex.5.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans+Extra+Condensed" rel="stylesheet">
<title>Document</title>
</head>
<body>
<img src="https://www.codewars.com/users/stefan835/badges/large" alt="codewars-badge">
<h1>Ex.5</h1>
<h3><a href="./Ex.4.html">Link to previos!</a></h3>
<h3><a href="./Ex.6.html">Link to next!</a></h3>
<p>Given an array of one's and zero's convert the equivalent binary value to an integer.
</p>
<p>Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1</p>
<h4>Examples:</h4>
<pre><i>Testing: [0, 0, 0, 1] ==> 1<br/>Testing: [0, 0, 1, 0] ==> 2<br/>Testing: [0, 1, 0, 1] ==> 5<br/>Testing: [1, 0, 0, 1] ==> 9<br/>Testing: [0, 0, 1, 0] ==> 2<br/>Testing: [0, 1, 1, 0] ==> 6<br/>Testing: [1, 1, 1, 1] ==> 15<br/>Testing: [1, 0, 1, 1] ==> 11</i></pre>
<h2>My solution</h2>
<div class="code">
<pre>const binaryArrayToNumber = arr => {<br/> return arr.reduce((prevEl, nextEl, index) => {<br/> return nextEl !== 0 ? prevEl + Math.pow(2, arr.length - index - 1) : prevEl + nextEl<br/> }, 0)<br/>};</pre>
</div>
<h2>Best solution</h2>
<div class="code">
<pre>const binaryArrayToNumber = arr => parseInt(arr.join(''), 2);</pre>
</div>
<h2 class="passed">PASSED</h2>
<h3>Time: 472ms</h3>
<script>
//MY SOLUTION
const binaryArrayToNumber = arr => {
return arr.reduce((prevEl, nextEl, index) => {
return nextEl !== 0 ? prevEl + Math.pow(2, arr.length - index - 1) : prevEl + nextEl
}, 0)
};
console.log(binaryArrayToNumber([1, 0, 1, 1])) // ==> 11
//BEST SOLUTION
// const binaryArrayToNumber = arr => parseInt(arr.join(''), 2);
</script>
</body>
</html>