Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of digits - which method is most efficient?

Tags:

There are more than one solution for finding the-number-of-digits in a given number.

For example:

Method-1:

int findn(int num) {     char snum[100];     sprintf(snum, "%d", num);     return strlen(snum); } 

Method-2:

int findn(int num) {     if (num == 0) return 1;     int n = 0;     while(num) {         num /= 10;         n++;     }     return n; } 

Method-3:

int findn(int num) {     /* math.h included */     return (int) log10(num) + 1; } 

The question is - what is the most efficient method? I know method-2 is O(n) but what about method-1 and method-3? How do I find the run-time complexity of library functions?

like image 592
Sangeeth Saravanaraj Avatar asked Mar 15 '12 13:03

Sangeeth Saravanaraj


People also ask

How do you count the number of digits in a number?

The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

How do I count the number of digits in Excel?

To use the function, enter =LEN(cell) in the formula bar and press Enter. In these examples, cell is the cell you want to count, such as B1. To count the characters in more than one cell, enter the formula, and then copy and paste the formula to other cells.

How do you count digits in Java?

Since, for loop doesn't have a body, you can change it to a single statement in Java as such: for(; num != 0; num/=10, ++count);


1 Answers

The following is even more efficient:

int findn(int num) {    if ( num < 10 )       return 1;    if ( num < 100 )       return 2;    //continue until max int } 

You could optimize this even further by doing a binary search, but that would be overkill.

like image 64
Luchian Grigore Avatar answered Sep 24 '22 03:09

Luchian Grigore