Finding binary gap highest number in php

This is just for training purpose

// you can write to stdout for debugging purposes, e.g. // print “this is a debug message\n”; function solution($n){

if(is_int($n) AND $n < 2147483647){ // write your code in PHP7.0

$binaryString = decbin($n);

$gap = 0;

$max = 0;

$lenght = strlen($binaryString);

$bin = str_split($binaryString);

for($x=0; $x < $lenght; $x++){

// if 1 then reset gap as it starts again

if($bin[$x] == 1){

if($gap > $max){

$max = $gap;

}

$gap=0;

}else{

$gap++; // increase the gap

}

}

return $max;

}else{

return 0;

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s