Last active
December 13, 2019 14:29
-
-
Save wachukxs/257bc54c513cfa85276698076252f2bb to your computer and use it in GitHub Desktop.
Simple solution to binary gap challenge from codility [https://app.codility.com/programmers/lessons/1-iterations/binary_gap/]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function BG(N){ | |
// https://www.w3resource.com/javascript-exercises/javascript-math-exercise-3.php | |
// https://codepen.io/w3resource/pen/Qxgpzw | |
// console.log(N, parseInt(N, 10).toString(2)); // N.toString(2) does the trick too | |
var k = parseInt(N, 10).toString(2); | |
var t = Array.from(k) | |
// console.log(t, t.indexOf('0')); | |
var r = new Array; | |
// works 100% but TODO; make sure it has 1 ... 0 ... 1 | |
// makes sure it has 0s and 1s after 0s | |
if (t.includes('0') && t.includes('1', t.indexOf('0'))) { | |
let i = 0; | |
for (let index = t.indexOf('0'); index < t.lastIndexOf('1') + 1; index++) { | |
// console.log('current index:', index) | |
const element = t[index]; | |
// console.log('current element:', element) | |
if (element == '0') { | |
i = i + 1; | |
} else { | |
r.push(i) | |
// console.log(i) // 'num:' | |
// calling BG(9); makes new index -1, why? | |
// recalibrate i | |
if (t.indexOf('0', index) != -1) { | |
i = 1; | |
index = t.indexOf('0', index) | |
} | |
// console.log('new index:', index) | |
} | |
} | |
// https://stackoverflow.com/a/52446467 | |
// console.log(...r) | |
return Math.max(...r); | |
} else { | |
// console.log(0); // 'uhmm, nothing' | |
return 0; | |
} | |
} | |
BG(32); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment