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?
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With