Counting Digits

A problem came up: how to count the number of digits in an integer? There were three solutions that I could think of: division, strings, and logarithms.

  • You can divide the integer by 10 until you get to zero. The number of divisions is equal to the number of digits.
  • You can convert the number to a string and get the length of the string.
  • You can take the ceiling of the base 10 log of the number.

In order to figure out which of these methods works best, I wrote a short python script. Starting with a 9 digit number, I ran the number through 1,000 iterations of each method, got the average calculation time, added another digit, and repeated indefinitely. The division method started showing significant decreases in speed at about 200 digits. The string method broke down at about 400 digits. The logarithm method ran with no decrease in calculation speed up to 47,387 digits. The process of adding an extra digit to the number took significantly more time than the 1,000 iterations of the digit count. Not wanting to let my computer's all day calculation spree go to waste, I present these findings and the algorithm here. Your mileage may vary, depending on the log implementation.

def numdigits(n):
    return int(math.ceil(math.log(n, 10)))