解决方案 »

  1.   


        int a=23;
        int result[31]={0};
        int test=1;
        int pos=0;    for(int i=0;i<=30;i++)
        {
            if((a&test)!=0)
            {
                result[pos]=test;
                pos++;
            }
            test=test<<1;
        }
      

  2.   

    public static void main(String[] args) {
    int number = 1025;
    int degree = 0;//二进制中值为1的个数
    for(int i=0;i<32;i++){
    if(((1<<i)&number)!=0){
    degree++;
    }
    }
    int[] array = new int[degree];
    int index = 0;
    for(int i=0;i<32;i++){
    if(((1<<i)&number)!=0){
    array[index++]=(1<<i);
    }
    }
    System.out.println(degree);
    System.out.println(Arrays.toString(array));
    }
      

  3.   

    public static Integer[]  intToIntegerList(int ind){
    List<Integer> list = new ArrayList<Integer>();
    int idx = 2;
    while(ind != 0){
    int x =idx/2;
    if(ind % idx != 0 ){
    list.add(x);
    ind -= x;
    }else if(ind / idx == 1){
    list.add(idx);
    ind = 0;
    break;
    }
    idx *= 2;
    }
    Integer[] a = new Integer[0];
    a=list.toArray(a);
    return a;
    }
    谢谢楼上两位,因为你们那样写的话,会多操作N多次,于是我从你们相反的方向出去最后算出写出来了,给大家分享一下
      

  4.   

      public static int[] intToIntegerList(int ind) {
        if (ind < 0) { // ind <= 0??
          throw new IllegalArgumentException();
        }
        int[] array = new int[31];
        int count = 0;
        for (int i = 1; i > 0; i <<= 1) {
          if ((ind & i) != 0) {
            array[count++] = i;
          }
        }
        int[] result = new int[count];
        System.arraycopy(array, 0, result, 0, count);
        return result;
      } 
      

  5.   

    没看懂“多操作N多次”的意思。我们几个用的都是位操作,虽然数学本质和你的一样,但是效率高很多倍。另外,前面的代码更新一下,减少不必要的循环和数组拷贝
      public static int[] intToIntegerList(int ind) {
        if (ind < 0) { // ind <= 0??
          throw new IllegalArgumentException();
        }
        int[] array = new int[Integer.bitCount(ind)];
        int count = 0;
        for (int i = 1; i > 0 && count < array.length; i <<= 1) {
          if ((ind & i) != 0) {
            array[count++] = i;
          }
        }
        return array;
      }