由网友(雾尽眉目清)分享简介:什么是找到的正整数的位数的最佳方法?What is the best method to find the number of digits of a positive integer?我发现这3种基本方式:I have found this 3 basic methods:转换为字符串conversion to...
什么是找到的正整数的位数的最佳方法?
What is the best method to find the number of digits of a positive integer?
我发现这3种基本方式:
I have found this 3 basic methods:
转换为字符串
conversion to string
String s = new Integer(t).toString();
int len = s.length();
循环
for loop
for(long long int temp = number; temp >= 1;)
{
temp/=10;
decimalPlaces++;
}
logaritmic计算
logaritmic calculation
digits = floor( log10( number ) ) + 1;
在这里,你可以计算出在大多数语言LOG10(X)= LN(X)/ LN(10)。
where you can calculate log10(x) = ln(x) / ln(10) in most languages.
首先,我认为该字符串的方法是最脏的一个,但我越去想它,我就越觉得这是最快的方法。或者是什么?
First I thought the string method is the dirtiest one but the more I think about it the more I think it's the fastest way. Or is it?
推荐答案
总是有这种方式:
n = 1;
if (i >= 100000000){i /= 100000000; n += 8;}
if (i >= 10000){i /= 10000; n += 4;}
if (i >= 100){i /= 100; n += 2;}
if (i >= 10){i /= 10; n += 1;}
相关推荐
最新文章