Created
September 16, 2016 13:43
-
-
Save eokoneyo/29110a692466c99b9f29c050cccd0582 to your computer and use it in GitHub Desktop.
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
/* | |
@description function for determining Binary Gap in binary numbers, | |
inspired by a codility test | |
*/ | |
function BinaryGap(N) { | |
var bin = N.toString(2); | |
//console.log(`We have been fed ${bin}`); | |
var lastIndex = 0; | |
var currentArr, highestArr = []; | |
var repeatCheck = 0; | |
//create an array that contains the right solution set (i.e. has the longest number of zeros) | |
for (var i=0; i<bin.length; i++) { | |
if( bin[i] === '0' ) { | |
//use repeatCheck as flag for when '0' follows another '0' | |
repeatCheck++; | |
var j; | |
if (repeatCheck>1) { | |
j = bin.slice(lastIndex, i+1); | |
//Add a 0 to the currentArr since its still has a 0 that we didnt catch | |
j = currentArr+'0'; | |
} else { | |
j = bin.slice(lastIndex, i+1); | |
} | |
//save the current solution | |
currentArr = j; | |
//increase index number for the lastIndex visited | |
lastIndex = i+1; | |
//compare if the currentArr is higher in length by our record highest | |
if (currentArr.length > highestArr.length) { | |
highestArr = currentArr; | |
} | |
} else { | |
//reset repeatCheck here since a 1 has been encountered | |
repeatCheck = 0; | |
} | |
} | |
var filter = Array.prototype.filter; | |
var findZeros = filter.call(highestArr, function (x){ | |
if(x === '0') { | |
return x; | |
} | |
}); | |
//return ZeroCount; | |
return findZeros.length; | |
} | |
var result = BinaryGap(bin); | |
console.log(`BinaryGap is ${result}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment