Skip to content

Instantly share code, notes, and snippets.

@dsebastien
Created June 21, 2021 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsebastien/f5c5b8b517bf2b5682a84742147019f3 to your computer and use it in GitHub Desktop.
Save dsebastien/f5c5b8b517bf2b5682a84742147019f3 to your computer and use it in GitHub Desktop.
Calculate the binary gap of the given number (expecting 1 ... < positive infinity)
function solution(input) {
//console.log("Validating input: ", input);
if(!input) {
throw new Error("The input must be defined");
}
if(isNaN(input)) {
throw new Error("The input value must be a number")
}
const parsedInput = parseInt(input, 10);
if(parsedInput < 1) {
throw new Error("The input value must be >= 0");
}
if(parsedInput === Number.POSITIVE_INFINITY) {
throw new Error("The input value should not be too big, otherwise calculations will be wrong");
}
// Get the binary version
// Reference: https://medium.com/@voricles/a-simple-solution-to-calculate-the-longest-length-of-binary-gap-of-an-integer-in-javascript-66b2fb05c740
const binaryString = parsedInput.toString(2);
// This works by splitting the string on the '1's, giving us an array of either empty strings or trailing zeroes
// Then, mapping each of those groups to return the current binary gap value or 0
const arr = binaryString.split('1').map((binaryGap, index, binaryArr) => {
return binaryArr[index + 1] != undefined ? binaryGap.length : 0;
});
// Returns the longest binary gap
const retVal = Math.max.apply(Math, arr);
//console.log("Longest binary gap: ", retVal);
return retVal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment