3

我需要一种方法来计算特定整数的位数。它也应该适用于负数。有任何想法吗?

4

9 回答 9

6

试试这个代码。它使用以 10 为底的对数:

public static int length(int integer) {
    if(integer==0) {
        return 1;
    } else if(integer<0) {
        return ((int)Math.log10(Math.abs(integer)))+1;
    } else {
        return ((int)Math.log10(integer))+1;
    }
}
于 2013-05-22T08:42:38.567 回答
5
(n < 0) ? String.valueOf(n).length() - 1 : String.valueOf(n).length();
于 2013-05-22T08:42:21.870 回答
3

绝对值函数去掉-如果存在的话,剩下的和其他答案类似。

String.valueOf(Math.abs(number)).length();
于 2013-05-22T08:45:32.637 回答
2

最快的方法:

    public final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999,
        9999999, 99999999, 999999999, Integer.MAX_VALUE };

    public static int getSize(int d) {
    if (d == Integer.MIN_VALUE)
        return 10;
    if (d < 0) {
        d = -d;
    }
    for (int i = 0;; i++)
        if (d <= sizeTable[i])
            return i + 1;
}

它的灵感来自Integer

 static int stringSize(int x) {
    for (int i=0; ; i++)
        if (x <= sizeTable[i])
            return i+1;
}
于 2013-05-22T08:44:27.070 回答
0
 Integer i=new Integer(340);
      if(i<0)
      System.out.println(i.toString().length()-1);
      else
          System.out.println(i.toString().length()); 
于 2013-05-22T08:48:50.103 回答
0

这应该有效:

digitCount = String.valueof(number).length();
if(number < 0 ) digitCount--;
于 2013-05-22T08:44:16.850 回答
0
public static int integerLength(int n)
{
 return Math.abs(n).toString().length();
}
于 2013-05-22T09:05:05.317 回答
0
public class Test
{
     public static void main(String []args)
     {
         int n = 423;
         int count = 0;

         while(n != 0) 
         {
             n = n / 10;
             count++;
         }
         System.out.println(count);
     }
}
于 2013-05-22T08:57:34.683 回答
0

通过除以直到零剩余来计数数字(这可以很容易地适应任何基数,或者只需更改参数声明就可以很长时间)。

public static int countDigitsDiv(int value) {
    if (value == 0)
        return 1;
    int result = 0;
    // we work with negative values to avoid surprises with Integer.MIN_VALUE
    if (value > 0)
        value = -value;
    // count the number of digits
    while (value < 0) {
        result += 1;
        value /= 10;
    }
    return result;
}

使用 Math.log10() (如果由于 double 的精度有限而将 value 重新声明为 long,这将无法正常工作):

public static int countDigitsLog(int value) {
    int result = 1;
    if (value > 0) {
        result += (int) Math.log10(value);
    } else if (value < 0) {
        result += (int) Math.log10(-((double) value));
    }
    return result;
}
于 2013-05-22T15:25:50.790 回答