Created
January 13, 2020 22:20
-
-
Save allucardster/16c27e73bb6a8b6d39b1b711aa7f73d3 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
<?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