Re: C function for returning number of digits?



Ingo Menger wrote:
Richard Bos schrieb:


Keith Thompson <kst-u@xxxxxxx> wrote:


"Luke Wu" <LookSkywalker@xxxxxxxxx> writes:

Ohh my.... didn't think it would be a two liner.......thank you
#include<math.h>

int numdigits(int n)
   return log10(n) + 1;

I don't think a floating-point solution is best here. A loop using integer arithmetic is likely to be faster and more accurate. For that matter, a binary search on a lookup table holding powers of 10 is likely to be even quicker.

*g* Never knock the simple solution. You're quite right, of course


How about:
  int length;
  char digits[100];   /* should be big enough even for 128 bit longs */
  sprintf(digits, "%d", n);
  length = strlen(digits) - (n<0 ? 1 : 0);

Boxing this code in a function and/or handling special cases (has 0 1
digit or none?) is left as exercise for the OP.


Is sprintf followed by a strlen actually any faster than log10? I'm dubious about it on modern hardware. Plus the additional test for sign.

How about a simple integer loop (destroys n, so make a copy
if you need to keep it)

  int length;
  while(n)
  {
    length++;
    n /= 10;
  }

but it still might be slower depending on the availability
of a hardware log instruction vs. integer division speed.

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
.



Relevant Pages

  • Re: Adding large numbers in C
    ... one of the numbers - or perhaps the result - is too big to store in an int. ... But carry /does/ matter. ... The second step is to calculate the carry, storing the result in C: ... Incidentally, the subtraction routine does similar juggling, so if M and N ...
    (comp.lang.c)
  • Re: Serialize/marshal/reverse engineer unknown structure
    ... other language/platform for that matter) to help you". ... I can almost do it portably, though in more complex examples padding ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: [C++] Binary Search Confusion
    ... This is a SIMPLE binary search which I am currently learning about ... int binarySearch ... I have a 15 element array, ... How do you find an entry in a phone book? ...
    (alt.comp.lang.learn.c-cpp)
  • RE: Insert Item in Sorted CListCtrl
    ... Binary Search and insert is proper way and I use it in my programs. ... int BinarySearch(CString szSearchData, int nLeft, int nRight, int* ... return nMiddle; ...
    (microsoft.public.vc.mfc)
  • Re: [PATCH 2.6.7] Parallel port detection via ACPI
    ... static int __init parport_pc_init_superio ... >parallel port, and it happens in all machines I have at hand. ... No matter the motherboard, ...
    (Linux-Kernel)