Counting Digits in a Number: Exploring Python Solutions

Photo by Mika Baumeister on Unsplash

Understanding the Problem: Before delving into solutions, let’s clarify the problem statement. We aim to determine the number of digits present in a given integer, irrespective of its sign.

Solution 1: String Conversion Approach: The first method involves converting the number to a string and then calculating its length. Python’s built-in string manipulation functions make this solution concise and intuitive.

number = 123456789
num_digits = len(str(number))
print("Number of digits:", num_digits)

Solution 2: Iterative Division: Alternatively, we can use an iterative approach where we repeatedly divide the number by 10 until it becomes zero, incrementing a counter with each division.

def count_digits(number):
count = 0
number = abs(number) # Ensure we work with the absolute value
while number != 0:
count += 1
number //= 10
return count

number = 123456789
num_digits = count_digits(number)
print("Number of digits:", num_digits)

Happy coding!

--

--