我有8个复选框,其值为1
,2
,4
,16
,256
,512
, 1024
,4096
。
取决于所选择的内容取决于我给出的数字,即:5 = 1&选择4,20 = 16& 4,528 = 512& 16
现在我了解如何通过手动计算或创建地图来找出选中的复选框。即
[
{ number: 1, boxes: [1] },
{ number: 2, boxes: [2] },
{ number: 3, boxes: [1,2] },
{ number: 4, boxes: [4] },
{ number: 5, boxes: [4,1] },
{ number: 6, boxes: [4,2] },
{ number: 7, boxes: [4,2,1] }
]
但这不是我要找的。 p>
即:
def test() {
def checkBoxList = getCheckBoxList(1536)
assert checkBoxList == [1024,512]
checkBoxList = getCheckBoxList(7)
assert checkBoxList == [4,2,1]
//etc
}
def getCheckBoxList(int number) {
//Magic code -- Returns [] of boxes based on number
}
答案 0 :(得分:0)
从2的下一个值开始,该值大于参数,然后减去其他倍数。适用于您的情况?
def getCheckBoxList(int number) {
def list = []
Integer filter = 1
while(filter < number) { filter *= 2 }
filter /= 2
while (filter != 0) {
if (filter <= number) {
list << filter
number -= filter
}
filter /= 2
}
list
}
assert getCheckBoxList(1536) == [1024,512]
assert getCheckBoxList(7) == [4,2,1]
assert getCheckBoxList(17) == [16, 1]
assert getCheckBoxList(15) == [8, 4, 2, 1]
assert getCheckBoxList(29) == [16, 8, 4, 1]
assert getCheckBoxList(528) == [512, 16]