dsg435665475 2014-01-08 22:40
浏览 70
已采纳

找出哪些唯一数字相加以产生结果数

On my site, I have multiple checkbox fields, where each input doubles in value from the previous, like this:

<form name=test>
<input type='checkbox' name='groupe' value = '1'>
<input type='checkbox' name='groupe' value = '2'>
<input type='checkbox' name='groupe' value = '4'>
<input type='checkbox' name='groupe' value = '8'>
<input type='checkbox' name='groupe' value = '16'>
etc...
</form>

I stock the fields selected (by the user) result in summing all of the values selected.

Let's say that the user had selected 4 and 1. In this case, I insert the sum of field values, which is 5. At this stage, after insert, my SQL table is:

test
 5

I need to retrieve the values selected to create this result number 5.

The information to do that are: - 31 (the max result, which is the sum of each field 1+2+4+8+16) - it is impossible to get a result value of 5 using 2+2+1, because an input cannot be selected twice;

I did a lot of searching to solve this, but I couldn't find anything helpful. How do I do this in SQL or PHP?

  • 写回答

3条回答 默认 最新

  • dongyuan2388 2014-01-08 22:50
    关注

    I'm not sure what the point of storing the sum and then recovering the individual values - why not store the separate values?

    That said, if you must, the algorithm is quite simple:

    <?php
        print_r(get_parts($argv[1]));
    
        function get_parts($number) {
            $res = array();
            for ($pow = 1; $pow <= 16; $pow <<= 1)
            {
               if ($pow & $number) {
                   array_push($res, $pow);
               }
            }
            return $res;
        }
    ?>
    

    This function will accept a number and return an array of the components:

    $ php test.php 5
    Array
    (
        [0] => 1
        [1] => 4
    )
    $ php test.php 31
    Array
    (
        [0] => 1
        [1] => 2
        [2] => 4
        [3] => 8
        [4] => 16
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算