你会如何计算一个整数的数字量?
(n < 0) ? String.valueOf(n).length() - 1 : String.valueOf(n).length();
试试看看这个代码。它采用对数的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;
}
}
这应该工作:
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;
}
比这更快的将是一个二进制搜索,但没有真正值得:) –
与Integer.MIN_VALUE的 – Durandal
绝对值函数摆脱0如果存在,则其余与其他答案相似。
String.valueOf(Math.abs(number)).length();
失败,你打我吧;-) –
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();
}
与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;
}
你会如何解决在纸面上的问题? –