Created
July 28, 2014 08:52
-
-
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
This file contains hidden or 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
<?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