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 = 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

 Live Demo

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

Updated on: 05-Feb-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements