在int

时间:2017-05-04 14:02:22

标签: java arrays binary bits

我需要创建一个方法

private static int[] inBinary(int number)

返回数字的二进制表示形式并将其存储在数组中,不带任何额外的零。

示例:如果我有十进制数2,则应返回其二进制值10而不是001000000010

问题是我的代码(对于dec号2)返回01(当我将其转换为void方法并且只打印二进制[i]时),而不是10.我的问题是,我怎么能&#34 ;反向" "结果" while循环的功能变量,以便它返回10而不是01,如何将所有数据存储在数组中。这就是我到目前为止所做的:

public static int[] inBinary(int number){
    if(number < 0){
        throw new IllegalArgumentException("Negative numbers not possible!");
    }
    int elements = 1; int result = 0; int[] binary = new int[elements]; 
    while(number != 0){
        elements++;
        result = number % 2;
             number /= 2;

             for(int i = 0; i < binary.length; i++){
                 binary[i] = result;

             }
    }
    return binary; 
  }
  public static void main (String[] args){
  System.out.println(inBinary(2));
  }

5 个答案:

答案 0 :(得分:0)

public static int[] shiftbits(int[] array){

    int[] shiftedArray = new int[array.length];
    int index = array.length - 1;
    for (int i = 0; i < array.length; i++) {
        shiftedArray[i] = array[index];
        index--;
    }

    return shiftedArray;

}

答案 1 :(得分:0)

我试着为你解决这个问题;我在某些部分使用util.List,因为我们不知道为它定义数组所产生的binery数有多长。 reverse方法用于反转二进制数组并删除额外的zeor;这是您的完整代码:

    public static void main(final String[] args) {

       System.out.println(reverse(inBinary(2)));
    }

    public static Integer[] inBinary(int number) {
       if (number < 0) {
          throw new IllegalArgumentException("Negative numbers not possible!");
       }
       int elements = 1;
       int result = 0;
       final List<Integer> binaryList = new ArrayList<Integer>();
       while (number != 0) {
          elements++;
          result = number % 2;
          number /= 2;
          binaryList.add(new Integer(result));
       }
       final Integer[] binary = new Integer[binaryList.size()];
       binaryList.toArray(binary);
       return binary;
   }

   static String reverse(final Integer arr[]) {
      boolean flag = false;
      String tmp = "";

      for (int i = arr.length - 1; i >= 0; i--) {
         if (arr[i].equals(new Integer(1)) && flag == false) {
             flag = true;
         }
         if (flag == true) {
             tmp += arr[i];
         }
      }
    return tmp;
  }

答案 2 :(得分:0)

这是一个自制的解决方案。它效率稍低,但它运行正常。另外,我可以解释一下:

public static int[] inBinary(int number) {
    // this will store the full binary array
    int[] binary = new int[Integer.SIZE];
    for (int i = Integer.SIZE - 1; 0 <= i; i--) {
        binary[i] = number % 2;
        // one shift to the right, basically divides with two
        // it's okay to change the incoming parameter as it's not a reference
        number = number >> 1;
    }

    // then we count the leading zeros
    int startIndex = 0;
    while (binary[startIndex] != 1) {
        startIndex++;
    }

    // Arrays.copyOfRange() is prohibited so we have to do it manually:
    // We allocate a shorter array
    int[] result = new int[Integer.SIZE - startIndex];
    // and copy the related numbers.
    for (int i = 0; i < Integer.SIZE - startIndex; i++) {
        result[i] = binary[startIndex + i];
    }

    return result;
}

答案 3 :(得分:0)

程序的非常简化的工作版本:

public static void inBinary(int number){
    if(number < 0){
        throw new IllegalArgumentException("Negative numbers not possible!");
    }

   //create an empty list and fill binary digits in it
   List<Integer> binaryDigitsList = new ArrayList<Integer>(); 
   while(number != 0){
        int digit=number%2;
        binaryDigitsList.add(digit);
        number=number/2;
    }
    //now reverse the list and fill it in array
    int[] binaryArr = new int[binaryDigitsList.size()];
    for(int k=binaryDigitsList.size()-1, index=0; k>=0 ; k--){
        binaryArr[index]=binaryDigitsList.get(k);
        index++;
    }

    //print contents of array
    for(int index=0;index<binaryArr.length;index++)
        System.out.println("BinaryArray["+index+"] = "+binaryArr[index]); 
  }

答案 4 :(得分:0)

  

假设您要使用数组。这里有一个例子

public class ExempleDecimalBinary2 {


      public static void main(String a[]){
             ExempleDecimalBinary2 obj = new ExempleDecimalBinary2();

             System.out.println("\nBinary for 2: ");
             obj.inBinary(2);
             System.out.println("\nBinary for 124: ");
             obj.inBinary(124);
             System.out.println("\nBinary for 45: ");
             obj.inBinary(45);
             System.out.println("\nBinary for 2147483647: ");
             obj.inBinary(2147483647);



          }
    public static void inBinary(int number){
        int binary[] = new int[1];

         int index = 0;
         while(number > 0){

             binary=(int[]) resizeArray (binary, index+1);

           binary[index++] = number%2;

           number = number/2;
         }

         for(int i = index-1;i >= 0;i--){

           System.out.print(binary[i]);
         }

    }



    private static Object resizeArray (Object oldArray, int newSize) {
           int oldSize = java.lang.reflect.Array.getLength(oldArray);
           Class elementType = oldArray.getClass().getComponentType();
           Object newArray = java.lang.reflect.Array.newInstance(
                 elementType, newSize);
           int preserveLength = Math.min(oldSize, newSize);
           if (preserveLength > 0)
              System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
           return newArray; }
}