What is the best method to find the number of digits of a positive integer?
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 calculation
digits = floor( log10( number ) ) + 1;
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?
Integer.toString(t, radix)
,temp /= radix;
(and correspondingly,numDigits++;
, as it's generalizing from decimal), orln(x) / ln(radix)
... – Blanklyfloor(ln(n + 0.5) / ln(10))
might help with precision loss... – Sonde