Skip to content

Instantly share code, notes, and snippets.

@allucardster
Created January 13, 2020 22:20
Show Gist options
  • Save allucardster/16c27e73bb6a8b6d39b1b711aa7f73d3 to your computer and use it in GitHub Desktop.
Save allucardster/16c27e73bb6a8b6d39b1b711aa7f73d3 to your computer and use it in GitHub Desktop.
<?php
/*
A binary gap within a positive integer N is any maximal
sequence of consecutive zeros that is surrounded by ones
at both ends in the binary representation of N.
Find longest binary gap from given N integer
*/
function longBinaryGap(int $a) : int
{
$bin = decbin($a);
$maxGapLen = 0;
$prevKey = null;
for ($key = 0; $key < strlen($bin); $key++){
$val = intval($bin[$key]);
if (1 === $val) {
if (!is_null($prevKey)) {
$gapLen = $key - $prevKey - 1;
if ($gapLen > $maxGapLen) {
$maxGapLen = $gapLen;
}
}
$prevKey = $key;
}
}
return $maxGapLen;
}
$arr = [9, 529, 20, 15, 32, 42, 147, 483, 647];
foreach($arr as $val) {
print_r([
'number' => $val,
'binary_number' => decbin($val),
'long_binary_gap' => longBinaryGap($val),
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment