求整数的位数。一般有几种方法,其一是转成字符串求,缺点是字符串耗时间长;另一种是用Math.log10();用log函数;还有一种用循环除以10的方式求出;最后一种,直接判断<10,<100,<1000,<10000……或许效率挺高吧,因为不需要计算。
其一:
private static int getNumLenght(long num){
num = num>0?num:-num;
return String.valueOf(num).length();
}
其二:
private static int getNumLenght(long num){
num = num>0?num:-num;
if (num==0) {
return 1;
}
return (int) Math.log10(num)+1;
}
其三:
private static int getNumLenght(long num){
if (num==0) {
return 1;
}
int lenght = 0;
for (long temp = num ; temp != 0; temp/=10){
lenght++;
}
return lenght;
}
最后一种老长老长,不写了。