Description
Sometimes you need to know how many digits are in an int. Converting to a string is O(n).
?
floor(log10(abs(n))) + 1 gives the digit count in O(1).
Reach for when
You need the number of digits in an integer without the O(n) cost of converting it to a string.
Runtime
O(1)
Visualization
Pseudocode
length(n) = floor(log10(abs(n))) + 1 # +1 because log10 counts the gaps
Code
import math
def length(n):
if n == 0:
return 1 # log10(0) is undefined
return int(math.log10(abs(n))) + 1