I have written this code to check which bits are on of an Integer (if represented in binary) in Java:
public static List<String> list(int val)
{
List<String> dummyList = new ArrayList<String>();
int bit = 1;
int x;
for(int i=0; i<32; i++)
{
x = bit;
if((x&val)!=0)
dummyList.add(String.valueOf(i+1));
bit = bit << 1;
}
return dummyList;
}
The above written code works fine. But it has a loop which runs 32 times (In Java integer is 32 bit long). I want to minimize this complexity. Please share the better solution. Thanks in advance.