Last active
May 16, 2020 22:53
-
-
Save sagarchauhan005/b5861f6dacc0a012e37f3430befa8419 to your computer and use it in GitHub Desktop.
Codility Binary Gap Demo Test solution
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
function solution($N) { | |
// write your code in PHP7.0 | |
if($N!=null){ | |
$bin = decbin($N); | |
$binArr = str_split($bin); | |
//print_r($binArr); | |
$pos = array_keys($binArr,1); | |
//print_r($pos); return; | |
$diff = []; | |
if(sizeof($pos)>1){ | |
for($i=0; $i<sizeof($pos); $i++){ | |
$curr = $pos[$i]; | |
$next = $i+1; | |
if(array_key_exists($next, $pos)){ | |
$large = $pos[$next]; | |
array_push($diff, (($large-$curr)-1)); | |
} | |
} | |
asort($diff); | |
$res = array_values($diff); | |
return $res[sizeof($res)-1]; | |
}else{ | |
return 0; | |
} | |
} | |
} | |
solution(32); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment