Skip to content

Instantly share code, notes, and snippets.

@embayer
Created July 28, 2014 08:52
Show Gist options
  • Save embayer/6a3b7f59579ec75efdf2 to your computer and use it in GitHub Desktop.
Save embayer/6a3b7f59579ec75efdf2 to your computer and use it in GitHub Desktop.
Resolve the power of two terms of a given sum using the binary system
<?php
// resolve the power of two terms of a given sum
// using the binary system
function resolvePowerOfTwo($sum)
{
$result = array();
// binary representation
$bin = decbin($sum);
// length
$len = strlen($bin);
// skip the zero in the array
$len--;
// counter
$j = 0;
for($i = $len; $i >= 0; $i--)
{
// current digit
$digit = substr($bin, $j, 1);
$j++;
if($digit == '1')
{
// save the digit binary representation
$result[] = pow(2, $i);
}
}
return $result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment