【问题标题】:Function passing each integer n and prints minimum number of bits required to store n as a signed integer函数传递每个整数 n 并打印将 n 存储为有符号整数所需的最小位数
【发布时间】:2015-10-25 04:15:57
【问题描述】:

在传递整数数组并确定存储有符号整数的最小位数时,我无法找到公式或找到要使用的正确条件。 我已经做了相反的事情来找到整数的范围(最小到最大)给定位数使用方程式:位 b:max = -2^(b-1) min = 2^(b-1)-1 谢谢你的帮助!

public static void main(String[] args) 
{
    int[] intAr = {2,15,16,100,1000,999999};

    printMinBits(intAr);
}

public static void printMinBits(int[] y)
{
    System.out.print("\n             min bits\nnumber       to store\n");
    for(int n = 0; n < y.length; n++)
    {    
        System.out.printf("%6d",y[n]);


        /*MISSING*/


        System.out.println("");
    }    
}        

最小位的输出应为:3、5、6、8、11、21(在表格中)

【问题讨论】:

标签: java arrays function int bits


【解决方案1】:

整数类具有内置的位计数和定位方法。获得最高位位置的简单数学运算,因此需要的最低位:

private static int minBitsNeeded(int i) {
    return 1 + Integer.SIZE - Integer.numberOfLeadingZeros(i);
}

所以在你的例子中填写 MISSING:

public static void printMinBits(int[] y)
{
    System.out.print("\n             min bits\nnumber       to store\n");
    for(int n = 0; n < y.length; n++)
    {    
        System.out.printf("%6d",y[n]);

        System.out.printf( "%15d\n", minBitsNeeded(y[n]) );
    }    
}   

【讨论】:

    【解决方案2】:

    此方法可用于查找存储有符号整数所需的最小位数

    public static int minBits(int n) {
        int b = 1;
        //If n is negative
        if(n < 0) {
            n *= -1;
        }
        while (n > 0) {
            n /=2;
            b++;
        }
    }
    

    【讨论】:

      【解决方案3】:

      据我所知,您需要一个函数来获取给定int 的位数。你可以用Integer.toBinaryString(int) 和类似的东西来做到这一点

      private static int getBitCount(int v) {
          String str = Integer.toBinaryString(v);
          int count = 0;
          for (char ch : str.toCharArray()) {
              if (ch == '0') {
                  count++;
              } else {
                  break;
              }
          }
          return 1 + str.length() - count;
      }
      

      然后您可以使用格式化的 io 和 for-each loop 打印您的表格。类似的东西

      public static void printMinBits(int[] y) {
          System.out.println("Number to store\t\tMin bits");
          for (int v : y) {
              System.out.printf("%d\t\t\t%d%n", v, getBitCount(v));
          }
      }
      

      我使用您提供的main 执行以获得

      Number to store     Min bits
      2                   3
      15                  5
      16                  6
      100                 8
      1000                11
      999999              21
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        • 2015-06-07
        相关资源
        最近更新 更多