# Number of digits in a decimal number

Printable View

• 11-04-2007
maverix
Number of digits in a decimal number
Hi All,

Given an integer n of ndigits, I want to write a function which returns a value which is 1 followed by (ndigits-1) number of zeroes.
Example: If I give 12345, I should get 10000

The below code does the same. However, I would like to know if there is a more efficient way(s) to obtain the same result. Kindly post your thoughts regarding this:

Code:

```int func(int n) {   int i;   for(i=1; n>10; n/=10,i*=10)           ;             return i; }```
Regards
maverix
• 11-04-2007
Salem
As in say
if ( n >= 10000 && n < 100000 ) result = 10000;
• 11-04-2007
maverix
Its not with only 5 digit integers, the integer can be any number between 1 and INT_MAX.

I would like to know if there is a way to reduce the number of iterations in the for loop, I just want to optimize the code so that it takes little time to give out the result.
• 11-04-2007
Adak
Your efficiency shouldn't be a problem. Your loop will only execute 1 time for each power of 10, so n = 1,000,000, is only 6 loops. That's less than the blink of your eye, even on a slow computer.

If your code is running slow, I'd certainly look for the cause, in it's other functions, not here.
• 11-04-2007
ZuK
You can combine division and test into one statement
Code:

```int func(int n) {   int i;   for(i=1; n/=10; i*=10);   return i; }```
Kurt
• 11-04-2007
maverix
Hi All,
Thanks for all the replies.

Hi Adak,
My code is not slow because of this function...and I am sure other parts of the code is also fine.
However, I just wanted to know if there is some other mathematical way using which I could get the result.

One way I thought of is mentioned below:
Ex:
n = 234567
chop off the left most significant digit
subract the number 34567 from 234567
divide the resulting number 200000 by the left most significant digit 2

I am finding it difficult to put the above into C code.
Also, I am not sure if this would improve the efficiency.

If there are any other ways to implement, please let me know.
I just wanted to know various methods to implement the same.

Cheers,
maverix
• 11-04-2007
Salem
Take my code and copy/paste it 9 times, for each of the possible powers of 10 which can be represented in 32-bits.

For even more efficiency, you can reduce this to at MOST 4 comparisons by arranging the cascade of if/else branches in the right way.
• 11-04-2007
Sang-drax
If you want the mathematical way, you can use logarithms, but Salem's way will be faster.