函数传递每个整数n并打印将n存储为有符号整数所需的最小位数

时间:2015-10-25 04:15:58

标签: java arrays function int bits

在传递整数数组并确定存储有符号整数的最小位数时,我无法找到公式或找到正确的条件。 我已经反过来使用公式找到给定位数的整数范围(min到max):位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(表中)

3 个答案:

答案 0 :(得分:1)

整数类有buitin位计数定位方法。简单的数学运算得到最高位,并因此需要最少的位:

private static int minBitsNeeded(int v) {
    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]) );
    }    
}   

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

据我所知,您需要一个函数来获取给定int的位数。你可以用docs

之类的东西做到这一点
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和Integer.toBinaryString(int)打印你的表格。像

这样的东西
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