Python program to count the number of digits in a number

Count the number of digits in a number

Problem description :

The program gets a number as input from the user and returns the number of digits in the number.

For example,

number = 845

Here for the above number the number of digits is equal to 3.

Sample input :

n = 1324

Sample output :

Number of digits = 4

Method 1 :

In this method, We are using a while loop until the number becomes zero.  "//" operator is used , it divides the number on its left by the number on its right, rounds down the answer, and returns a whole number.

For example, 

45 // 10 = 4

762 // 10 = 76

After performing the division operation the count variable is increased by one.

Procedure :

1. Start.

2. Get the number as input from user and store it in a variable.

3. Initialize digit count variable as 0.

4. Loop (until n = 0)

    => increment digit count

    => num = num // 10

5. Print digit count.

6. End. 

Code :

#Get the number as input from the user and store it in a variable 

n = int(input("Enter the number : "))

#Initialize digit count as 0

digit_count = 0

while(n!=0):

        #increment digit count

digit_count+=1

        #number is divided using modulus operator

n=n//10

#print the digit count

print("Number of digits = ", digit_count)

Output screenshot :

Count the number of digits in a number
Digit count - Output 1



Method 2 :

In this method, the number is converted into a string. The length of the string will be equal to the number of digits in the number.

Procedure :

1. Start.

2. Get the number as input from the user and store it in a variable.

3. Convert the number into a string using type conversion and store it in a variable.

4. Print the length of string which is equal to the  number of digits.

5. End

Code :

#Get the number as input from user and store it in a variable.

n = int(input("Enter the number : "))

#Convert the number to string using type conversion

s = str(n)

#print the length of the string

print("Number of digits = ", len(s))

Output screenshot :

Count the number of digits in a number
Digit count - Output 2


Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

What's your name, Tuple - HackerRank solution in python