如何计算整数的位数?

3

我需要一种方法来计算一个整数有多少位数字,同时它也应该适用于负数。有什么想法吗?


你会如何在纸上解决这个问题? - Colonel Panic
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;
    }
}

简洁高效。你可以用 return ((int)Math.log10(-integer)) + 1; 替换 return ((int)Math.log10(Math.abs(integer)))+1; - assylias
0是一个数字。真正的问题是:-2是两位数还是只有一位数? :-) - paxdiablo
1
将返回值更改为1,以处理0的情况。 - Gregoran Bregovic
这将会失败,因为 Integer.MIN_VALUE。常被忽视的边界情况:Integer.MIN_VALUE == -Integer.MIN_VALUE。 - Durandal

5
(n < 0) ? String.valueOf(n).length() - 1 : String.valueOf(n).length();

只需要检查 number 是否小于0,而不是字符串值。 :) - Achrome
“-”会被视为数字,所以应该像这样:number < 0 ? String.valueof(number).length() - 1 : String.valueof(number).length(); - Alexandre Lavoie
感谢您的建议,已经修复了这些问题。 - Adam Siemion
零怎么办?这是一个哲学问题...;-) - Hans Frankenstein
在我看来,“0”是一个数字,这段代码在这种情况下就会产生这个结果 :) - Adam Siemion

3

绝对值函数会去掉其中的-符号,剩余部分与其他答案类似。

String.valueOf(Math.abs(number)).length();

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;
}

1
比这更快的是二分查找,但并不值得。 :) - Marko Topolnik
2
失败,返回 Integer.MIN_VALUE。 - Durandal

0
 Integer i=new Integer(340);
      if(i<0)
      System.out.println(i.toString().length()-1);
      else
          System.out.println(i.toString().length()); 

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);
     }
}

0
public static int integerLength(int n)
{
 return Math.abs(n).toString().length();
}

失败,返回 Integer.MIN_VALUE。 - Durandal

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()(如果 value 被重新声明为 long 类型,这种方法将无法正常工作,因为 double 类型的精度有限):

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;
}

0

这应该可以工作:

digitCount = String.valueof(number).length();
if(number < 0 ) digitCount--;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接