Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to get number of digits on a number? [duplicate]

I have do detect the amount of digits on a number. For example, 329586 has 6 digits.

What I done, is simply parsing the number to string, and getting the string length, like:

number.toString().length()

But, is there a fastest way to count digits on a number? I have to use this method several times, so I think using toString() can impact performance.

Thanks.

like image 918
JoaaoVerona Avatar asked Mar 23 '13 14:03

JoaaoVerona


2 Answers

Math.floor(Math.log10(number) + 1)
// or just (int) Math.log10(number) + 1

For example:

int number = 123456;
int length = (int) Math.log10(number) + 1;
System.out.println(length);

OUTPUT:

6
like image 124
Eng.Fouad Avatar answered Oct 22 '22 12:10

Eng.Fouad


how about this homebrewed solution:

int noOfDigit = 1;
while((n=n/10) != 0) ++noOfDigit;
like image 41
TravellingGeek Avatar answered Oct 22 '22 13:10

TravellingGeek