You can use a bitmask to try to shorten the cycle time. You add a few operations, but maybe do half the cycle:
public static List<String> list(int val) {
List<String> dummyList = new ArrayList<String>();
int loop = 32;
if((val & 0xFFFF0000) == 0){
loop = 16;
}
int bit = 1;
int x;
for (int i = 0; i < loop; i++) {
x = bit;
if ((x & val) != 0) {
dummyList.add(String.valueOf(i + 1));
}
bit <<= 1;
}
return dummyList;
}
This will potentially increase the time depending on the input.
You can also halve the cycle by doing two bits at a time:
public static List<String> list(int val) {
List<String> dummyList = new ArrayList<String>();
int bit = 3;
int x;
for (int i = 0; i < 32; i += 2) {
x = (bit & val);
switch (x) {
case 1:
dummyList.add(String.valueOf(i + 1));
break;
case 2:
dummyList.add(String.valueOf(i+2));
break;
case 3:
dummyList.add(String.valueOf(i+1));
dummyList.add(String.valueOf(i+2));
break;
default:
}
val >>= 2;
}
return dummyList;
}
source
share