php - maximum gap between two 1s in a binary equivalent of a decimal number -
php - maximum gap between two 1s in a binary equivalent of a decimal number -
i want write programme find maximum gap between 2 1s in binary equivalent of decimal number. illustration 100101: gap 2 , 10101: gap 1.
<?php $numbergiven = 251; $binaryform = decbin($numbergiven); $status = false; $count = 0; for($i = 0; $i < strlen($binaryform); $i++) { var_dump($binaryform[$i]); if($binaryform[$i] == 1) { $status = false; $count = 0; } else { $status = true; $count += 1; } } echo "count = " . $count . "<br>"; echo $binaryform; ?>
but not successfull..
i utilize binary right-shift operator >>
, iteratively shift 1 bit , check if current rightmost bit 1
until i've checked bits. if 1
found, gap between previous 1
calculated:
foreach(array(5,17,25,1223243) $number) { $lastpos = -1; $gap = -1; // means there 0 or excatly 1 '1's // php_int_size contains number of bytes integer // consume on system. value * 8 number of bits. for($pos=0; $pos < php_int_size * 8; $pos++) { if(($number >> $pos) & 1) { if($lastpos !== -1) { $gap = max($gap, $pos - $lastpos -1); } $lastpos = $pos; } } echo "$number " . decbin($number) . " "; echo "max gap: {$gap}\n"; }
output:
class="lang-none prettyprint-override">5 101 max gap: 1 17 10001 max gap: 3 25 11001 max gap: 2 1223243 100101010101001001011 max gap: 2
php algorithm
Comments
Post a Comment