Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a program in Python to count the number of digits in a given number N
Let's suppose we have given a number N. The task is to find the total number of digits present in the number. For example,
Input-1 ?
N = 891452
Output ?
6
Explanation ? Since the given number 891452 contains 6 digits, we will return '6' in this case.
Input-2 ?
N = 74515
Output ?
5
Explanation ? Since the given number 74515 contains 5 digits, we will print the output as 5.
The Approach Used to Solve This Problem
We can solve this problem in the following way:
Take input 'n' as the number.
A function
countDigits(n)takes input 'n' and returns the count of the digit as output.Iterate over all the digits of the number and increment the counter variable.
Return the counter.
Method 1: Using Division and Loop
This method repeatedly divides the number by 10 until it becomes 0 ?
def countDigits(n):
ans = 0
while n:
ans = ans + 1
n = n // 10
return ans
n = 45758
print("Number of digits in the given number:", countDigits(n))
The output of the above code is ?
Number of digits in the given number: 5
Method 2: Using String Conversion
Convert the number to a string and return its length ?
def countDigits(n):
return len(str(n))
n = 891452
print("Number of digits in the given number:", countDigits(n))
The output of the above code is ?
Number of digits in the given number: 6
Method 3: Using Logarithm
Use the mathematical property that the number of digits in a positive integer n is floor(log10(n)) + 1 ?
import math
def countDigits(n):
if n == 0:
return 1
return int(math.log10(n)) + 1
n = 74515
print("Number of digits in the given number:", countDigits(n))
The output of the above code is ?
Number of digits in the given number: 5
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Division Loop | O(log n) | O(1) | Understanding logic |
| String Conversion | O(log n) | O(log n) | Simple and readable |
| Logarithm | O(1) | O(1) | Fastest for large numbers |
Conclusion
The string conversion method is the simplest and most readable approach. Use the division method to understand the underlying logic, or the logarithm method for optimal performance with large numbers.
