Calculating the Number of Digits in an Integer
Sometimes it can be handy to calculate the number of digits in an integer for various mathematical calculations.
In C++
#include <math.h>
double len(double n) {
if n == 0:
return 1
double l = floor ( log10 ( n ) ) + 1; /* Number of digits in n */
long unsigned int len = int(l); /* Save it to an integer instead */
return len;
}
In Python
from math import log10, floor
def length(n):
if ( n == 0 ) { return 1; }
return floor( log10( n ) ) + 1
January 20th, 2007 at 3:04 am
Check this out for a few interesting C bit hacks: http://graphics.stanford.edu/~seander/bithacks.html
January 20th, 2007 at 1:20 pm
Awesome, thanks Elliott :)
April 11th, 2007 at 2:04 pm
log10(0) is undefined, so this function should be modified to return 1 if n == 0
April 11th, 2007 at 6:19 pm
Good point :)
April 12th, 2007 at 4:45 pm
And in php:
$digits = strlen($int);:)April 12th, 2007 at 6:01 pm
@Afterlife(69): That’s not mathematical :)
April 12th, 2007 at 7:21 pm
xD its easy tho ;)