Count number of digits in a given integer
To count the number of digits in a number we have to divide that number by 10 until it becomes 0 or less than 0. If you divide any number by 10 and store the result in an integer then it strips the last digit. So we have to apply the same logic here also.
Logic
After taking the input from the user, run one while loop that runs until the user given number becomes 0. Inside the loop for each iteration increase the counter variable by one and divide the user given number by 10 and store it in the same variable again.
Notice here we are using /= operator that performs division and stores the result in the same variable again.
Once the loop is over we have to print counter variable “count” containing the total number of digits.
Program
# Take input from user num = int(input("Enter any number : ")) # Store to temporary variable. temp = num count = 0 while (temp != 0): # Increment counter count += 1 # Remove last digit of 'temp' temp = int(temp / 10); print("\nTotal digits in", num, ":", count)
Output
Enter any number : 123456
Total digits in 123456 : 6