How do I return an integer array the sum of which

2019-09-22 12:55发布

问题:

Input: any number in 1-15 or 64-79 range which is a sum of either (1, 2, 4, 8, 64) in any combination

Output: an array of integers from this list: (1, 2, 4, 8, 64) the sum of which equals the input number.

e.g.

  • input 72, output array(8, 64)
  • input 13, output array(1, 4, 8)

回答1:

Since you have not included your code in the question, no one can help you with your code. But here is a general approach without any code that should work for this problem.

Start with your input number and an empty array to hold the sum elements. Iterate over your array of addends in descending order, appending each one to your sum array and subtracting it from the input number until the input number reaches zero.



回答2:

mkasberg provided the solution:

   $in = 72;
   $out = array();
   $a = array_reverse(str_split((string)decbin($in)));
    foreach($a as $k => $v){
       if ($v != "0") array_push($out, pow(2,$k));
    }