你会如何计算一个整数的数字量?

问题描述:

我需要一种方法来计算特定整数所具有的位数。它也应该用于否定数字。有任何想法吗?你会如何计算一个整数的数字量?

+0

你会如何解决在纸面上的问题? –

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

不适用于负数...... –

+0

只需检查'number'是否小于0.不是字符串值。 :) – Achrome

+0

'-'会算作一个数字,所以应该像'数字

试试看看这个代码。它采用对数的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; 
    } 
} 
+0

尼斯和高效。你可以替换'回报((INT)Math.log10(Math.abs(整数)))+ 1;由''回报((INT)Math.log10(-integer))+ 1;' – assylias

+0

是0一或零数字? –

+0

0是一位数字。 _real_问题是:是'-2'还是两个数字? :-) – paxdiablo

这应该工作:

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

最快的方法:

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

比这更快的将是一个二进制搜索,但没有真正值得:) –

+2

与Integer.MIN_VALUE的 – Durandal

绝对值函数摆脱0如果存在,则其余与其他答案相似。

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

失败,你打我吧;-) –

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

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

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

与Integer.MIN_VALUE的失败 – Durandal

计数位数除以直到零具遗体(这可以通过仅仅改变参数声明很容易地适应任何基数,或用于长)。

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()(这将无法正常如果值重新声明,只要是由于增加一倍的精度有限的工作):

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