Java 计算n对应的二进制位上有几个1,分别在什么位置?
Java计算n的二进制位上有几个1,分别在什么位置
public List<Integer> getBinOneCount(int n){
List<Integer> ar = new ArrayList<>();
int index=0;
while(n>0){
int x=n&1<<index;
if(x!=0){
ar.add(index+1);
n=n-(1<<index);
}
index++;
}
return ar;
}
public static void main(String[] args) {
Test2 t = new Test2();
System.out.println(t.getBinOneCount(10));
}
1:判断n是否大于0;
2:让n分别于2^0,2^1,2^2……2^index做 与操作,结果不为0代表n为上有1,记录到集合;
3:index 位上为1,则需要n减去2^index。
例如10
二进制 1010
index | n | &的对象 | &的结果 | list | &操作后n的值 |
0 | 1010 | 2^0=1=0001 | 0000 | {} | 1010 |
1 | 1010 | 2^1=2=0010 | 0010 | {2} | 1010-0010=1000 |
2 | 1000 | 2^2=4=0100 | 0000 | {2} | 1000 |
3 | 1000 | 2^3=8=1000 | 1000 | {2,4} | 1000-1000=0000 while结束 |
结果就是10 对应的二进制上有2个1,分别在从右往走数 第2和第4个(这里默认最右边为1)