Count Number of Digits in Java
In this class, We discuss Count Number of Digits in Java.
The reader should have prior knowledge of loops in Java. Click Here.
Question:
Given an integer.
Our task is to find the number of digits in the integer.
Example:
Input: 56789
Output: 5
Logic:
Take the number 5678.
5678/10 = 567
567/10 = 56
56/10 = 5
5/10 = 0
Divide the number by ten until we get zero.
If the number has four digits, we get zero after four times
Similarly, If the number has five digits, we get zero after five times.
So we use a loop until we get zero.
Each time in the loop, we increment the count.
We take a variable count and increment.
The below diagram shows the code.