我需要一种方法来计算一个整数有多少位数字,同时它也应该适用于负数。有什么想法吗?
我需要一种方法来计算一个整数有多少位数字,同时它也应该适用于负数。有什么想法吗?
尝试使用这段代码。它使用以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-2
是两位数还是只有一位数? :-) - paxdiablo(n < 0) ? String.valueOf(n).length() - 1 : String.valueOf(n).length();
number
是否小于0,而不是字符串值。 :) - Achromenumber < 0 ? String.valueof(number).length() - 1 : String.valueof(number).length();
- Alexandre Lavoie绝对值函数会去掉其中的-
符号,剩余部分与其他答案类似。
String.valueOf(Math.abs(number)).length();
最快的方法:
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;
}
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();
}
通过除以零来计算数字(这可以很容易地适应任何基数,或者通过改变参数声明来适应长整型)。
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;
}
这应该可以工作:
digitCount = String.valueof(number).length();
if(number < 0 ) digitCount--;