# python - 在python中，整数的长度

``````
import math
digits = int(math.log10(n))+1

``````

``````
import math
if n > 0:
digits = int(math.log10(n))+1
elif n == 0:
digits = 1
else:
digits = int(math.log10(-n))+2 # +1 if you don't count the '-'

``````

``````
timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop

timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop

timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop

``````

``````
math.floor(math.log10(n))+1

``````

``````
from math import log10
digits = lambda n: ((n==0) and 1) or int(log10(abs(n)))+1

``````

``````
def num_digits(num, number_of_calls=1):
"Returns the number of digits of an integer num."
if num == 0 or num == -1:
return 1 if number_of_calls == 1 else 0
else:
return 1 + num_digits(num/10, number_of_calls+1)

``````

## 所有math.log10解决方案都会给你带来问题，

``````
def getIntegerPlaces(theNumber):
if theNumber <= 999999999999997:
return int(math.log10(theNumber)) + 1
else:
counter = 15
while theNumber >= 10**counter:
counter += 1
return counter

``````
``````
def length(i):
return len(str(i))

``````

``````
import math

def gui():
n=int(input("Enter any number"))
if n>0:
print(int(math.log10(n))+1)
elif n==0:
print(1)
else:
print(int(math.log10(-n))+1)**

``````