I try to write a function to count number digits,and by the way,I try to compare the efficiency of the different way. 1.the lenstr(i) way:
def nDigits(i):
return len(str(i))
for i in range(100000):
print nDigits(i)
it takes about 143.75s
2.the log10 way:
import math
def nDigits(i):
if i > 0:
n = int(math.log10(i)) + 1
elif i == 0:
n = 1
else:
n = int(math.log10(-i)) + 2
return n
for i in range(100000):
print nDigits(i)
it takes about 144.35s
3.the division way:
def nDigits(i):
t = 0
while i > 0:
t += 1
i /= 10
return t
for i in range(100000):
print nDigits(i)
it takes about 143.43s
4.the division way in c:
#include<stdio.h>
int digits(int num){
int i = 0;
while (num > 0){
i += 1;
num /= 10;
}
return i;
}
void main(){
int i = 0;
while (i < 100000){
i += 1;
printf("%d",digits(i));
}
}
it takes about 0.07s
Is the C is 2000 times better than python...or There is a better way for python to counting number digits. thx guys,plz help me.