Re: C function for returning number of digits?
- From: Kevin Handy <kth@xxxxxxx>
- Date: Tue, 29 Nov 2005 10:57:21 -0700
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 =---- .
- Follow-Ups:
- Re: C function for returning number of digits?
- From: Jordan Abel
- Re: C function for returning number of digits?
- References:
- C function for returning number of digits?
- From: Luke Wu
- Re: C function for returning number of digits?
- From: Chris McDonald
- Re: C function for returning number of digits?
- From: Luke Wu
- Re: C function for returning number of digits?
- From: Keith Thompson
- Re: C function for returning number of digits?
- From: Richard Bos
- Re: C function for returning number of digits?
- From: Ingo Menger
- C function for returning number of digits?
- Prev by Date: Re: direct string manuplation not working
- Next by Date: Re: Advanced C
- Previous by thread: Re: C function for returning number of digits?
- Next by thread: Re: C function for returning number of digits?
- Index(es):
Relevant Pages
|