1

I know I can do:

n = floor(log10(i)) + 1;

Or I can do a quick loop:

while(i) {
  n++;
  i/=10;
}

Is there any better way than a complicated math operation, or a loop to achieve the goal? For example: if i = 1234, then n = 4.

SwiftMango
  • 15,092
  • 13
  • 71
  • 136
  • Base 10 operations and "quickly" tend not to go hand in hand. What do you need the length for and why does it need to be fast? – Carl Norum Oct 09 '13 at 22:27
  • 2
    Have you actually determined that this part of your code needs to be faster? – chris Oct 09 '13 at 22:27
  • what about `i <= 0` ? note that in this case log10(i) is not defined. Similarly, your loop code doesn't work for i = 0 – Arunas Oct 09 '13 at 22:36
  • @Arunas in my code I am assuming i is positive. – SwiftMango Oct 09 '13 at 22:36
  • Better than "an overly complicated math operation"?! What do you think the "number of digits" *is* other than some "complicated math operation"? It's the logarithm of the number after all... – Kerrek SB Oct 09 '13 at 22:55
  • @texasbruce - that sort of assumption should be stated in the question. However, you really should look into the duplicate question as has been noted by others, as the solutions are very elegant and fast in most cases. – Arunas Oct 09 '13 at 23:14

2 Answers2

1

The shortest way I know of (not computationally, just in terms of typing) is to call snprintf(3):

int n = snprintf(NULL, 0, "%d", i);
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
0

convert it to a string (itoa) and count the number of characters? (might be not the best performance-wise though)

Ashalynd
  • 12,363
  • 2
  • 34
  • 37