Python programs to count the digits in an integer have been shown here. For example, if a number is 12345, the total number of digits is 5. The algorithm, pseudocode and time complexity of the programs have also been covered below.
Page content(s):
1. Algorithm to count the digits in an integer
1. Take a number x as input.
2. Initialize a counter to 0 say c = 0.
3. Perform x = x / 10 and Increment c by 1 i.e. c = c + 1
4. If x = 0 stop the process and display c as output else go to step 3.
2. Pseudocode to count the digits in an integer
Input : A number $n$
Output : Total no of digits in $n$
1. Procedure countDigits($n$):
2.
3.
4.
5.
6.
7.
8.
9.
10. End Procedure
3. Time complexity to count the digits in an integer
Time Complexity: O(log(n))
Where n is the input number.
4. Program & output to count the digits in an integer
4.1. Python Program & output to count the digits in an integer using iteration
# ********************************************** # alphabetacoder.com # Python program to count the number of digits # in an integer using iterative approach # ********************************************** # initialize count = 0 # take input of the number num = int(input("Enter the integer = ")) # count the digits if num == 0: count = 1 else: while num != 0: num = num // 10 count = 1 # display result print("Number of digits = ", count)
Output
Case 1:
Enter the integer = 8912
Number of digits = 4
Case 2:
Enter the integer = 5413896
Number of digits = 7
4.2. Python Program & output to count the digits in an integer using recursion
#********************************************** # alphabetacoder.com # Python program to count the number of digits # in an integer using recursive approach #********************************************** # recursive function to calculate # no of digits in an integer def count_digit(num): if num // 10 == 0: return 1 else: # call function return 1 + count_digit(num / 10) def main(): # take input of the number num = int(input("Enter the integer = ")) # count the digits by calling function count = count_digit(num) # display result print("Number of digits = ", count) # driver code main()
Output
Case 1:
Enter the integer = 8912
Number of digits = 4
Case 2:
Enter the integer = 0
Number of digits = 1
4.3. Python Program & output to count the digits in an integer using logarithm
#********************************************** # alphabetacoder.com # Python program to count the number of digits # in an integer using logarithm #********************************************** import math # take input of the number num = int(input("Enter the integer = ")) # count the digits using logarithm if num == 0: count = 1 else: count = math.floor(math.log10(num) + 1) # display result print("Number of digits = ", count)
Output
Case 1:
Enter the integer = 3456
Number of digits = 4
Case 2:
Enter the integer = 1234567
Number of digits = 7