Skip to content

Instantly share code, notes, and snippets.

@SabrinaMarkon
Last active January 11, 2017 19:03
Show Gist options
  • Save SabrinaMarkon/76f1ae34bda06e544a62e7c92c04b93d to your computer and use it in GitHub Desktop.
Save SabrinaMarkon/76f1ae34bda06e544a62e7c92c04b93d to your computer and use it in GitHub Desktop.
Sabrina Markon - Algorithms - For a given integer (from STDIN), convert to binary then find out the greatest number of 1's in a row in the binary number.
<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%d",$n);
function addToStack($x, &$stack) {
$remainder = $x % 2;
$nextx = ($x - $remainder)/2;
array_unshift($stack, $remainder);
if ($nextx >= 1) {
addToStack($nextx, $stack);
} else {
return $stack;
}
}
$stack = array();
addToStack($n, $stack);
$count = 0; // running total of 1s in a row.
$highestcount = 0; // highest total of 1s in a row before a 0 is encountered.
for ($i = 0; $i < count($stack); $i++) {
if ($stack[$i] === 1) {
// add to running count of 1s and totalcount:
$count++;
} else {
// Every time a zero is encountered AND after the for loop finishes to consider array that ends in groups of 1s:
// if count is bigger than the existing highestcount (which is zero for the first set of 1s encountered),
// assign it to highestcount as the new highest total of 1s in a row:
if ($count > $highestcount) {
$highestcount = $count;
}
// we found a 0 so reset the running total:
$count = 0;
}
}
if ($count > $highestcount) {
$highestcount = $count;
}
echo $highestcount;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment