Python Program to Find Number of Digits in a Number
len(str(abs(number))), which counts all digits ignoring the sign.Examples
How to Think About It
Algorithm
Code
number = int(input("Enter a number: ")) num_digits = len(str(abs(number))) print("Number of digits:", num_digits)
Dry Run
Let's trace the number 12345 through the code
Input number
number = 12345
Absolute value
abs(number) = 12345
Convert to string
str(abs(number)) = '12345'
Count digits
len('12345') = 5
Print result
Output: Number of digits: 5
| Step | Value |
|---|---|
| Input number | 12345 |
| Absolute value | 12345 |
| String conversion | '12345' |
| Length (digits) | 5 |
Why This Works
Step 1: Handle negative numbers
Using abs() removes the negative sign so it doesn't count as a digit.
Step 2: Convert number to string
Converting to string lets us count each digit easily with len().
Step 3: Count digits
The length of the string is exactly the number of digits in the number.
Alternative Approaches
number = int(input("Enter a number: ")) count = 0 num = abs(number) if num == 0: count = 1 else: while num > 0: num //= 10 count += 1 print("Number of digits:", count)
import math number = int(input("Enter a number: ")) num = abs(number) if num == 0: count = 1 else: count = int(math.log10(num)) + 1 print("Number of digits:", count)
Complexity: O(d) time, O(d) space
Time Complexity
Converting the number to a string takes time proportional to the number of digits d, so it is O(d).
Space Complexity
The string conversion uses extra space proportional to the number of digits, so O(d).
Which Approach is Fastest?
The string method is simple and fast for most uses. The loop method uses constant space but may be slower for very large numbers. The logarithm method is efficient but requires math functions and special zero handling.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String conversion | O(d) | O(d) | Simplicity and readability |
| Loop division | O(d) | O(1) | No string conversion allowed |
| Logarithm | O(1) | O(1) | Mathematical approach, large numbers |
len(str(abs(number))) for a quick and simple digit count.abs() first.