
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Digits in a Given Number Using Python
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 = 0074515
Output −
5
Explanation − Since the given number 0074515 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.
Example
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))
Output
Running the above code will generate the output as,
5
Advertisements