How do I return an integer array the sum of which equals to a given number in php? [closed]

♀尐吖头ヾ 提交于 2019-12-13 23:24:06

问题


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));
    }


来源:https://stackoverflow.com/questions/30131528/how-do-i-return-an-integer-array-the-sum-of-which-equals-to-a-given-number-in-ph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!