Created
January 17, 2016 02:36
-
-
Save rafaelbernard/664bc481cf649c7f4aa4 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 | |
function solution($N) { | |
//print "N: $N\n"; | |
// write your code in PHP5.5 | |
$bin = base_convert($N, 10, 2); | |
$sbin = trim((string) $bin); | |
//print "sbin: $sbin\n"; | |
$any_zero = strpos($sbin, '0'); | |
//print "any zero: ". var_dump($any_zero, true). "\n"; | |
// The function should return 0 if N doesn't contain a binary gap | |
if ($any_zero === false) return 0; | |
$array = explode('1', trim($sbin)); | |
usort($array, "cmp"); | |
//print_r($array); | |
foreach($array as $key => $value) { | |
$find = "1{$value}1"; | |
//print "value: $value\n"; | |
//print "find: $find\n"; | |
if ($value == '') return 0; | |
$strpos = strpos($sbin, $find); | |
//print "sp: " . $strpos . "\n"; | |
if ($strpos !== false) return strlen($value); | |
} | |
return 0; | |
} | |
function cmp($a, $b) { | |
$la = strlen($a); | |
$lb = strlen($b); | |
if ($la == $lb) return 0; | |
return ($la > $lb) ? -1 : 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment