Java Program to count the digits in a given number.
Objective
Write a Java program to count the number of digits in an integer.
Algorithm / Approach
- Read an integer
nfrom the user. - Initialize a counter variable
cto 0. - Use a
whileloop that runs as long asn > 0. - Inside the loop, divide
nby 10 (n = n / 10) to strip off the last digit. - Increment the counter
cby 1. - Print the counter when the loop terminates.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a Num: ");
int n = s.nextInt();
int c=0;
while(n>0) {
n = n/10;
c++;
}
System.out.print("Digits = "+c);
}
}
Expected Output
Enter a Num: 12345 Digits = 5
Explanation of the Program
- The program repeatedly divides the number by 10 using integer division.
- Since
nis an integer, dividing by 10 effectively truncates the rightmost decimal digit. - For example, 12345 / 10 becomes 1234. The loop runs exactly once for each digit until the number shrinks to 0.
- The counter tracks how many times this division occurred, giving the total digit count.
Complexity
Time Complexity
O(log10(n)) - The loop runs as many times as there are digits.
Space Complexity
O(1)
Common Mistakes
- Not handling the number 0 correctly. If 0 is inputted, the condition
n > 0immediately fails, and it reports 0 digits instead of 1. - Running into an infinite loop by using a double instead of an integer for
n.