Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to count the digits in a given number.

Java Code Example — Simple Programs

ADVERTISEMENT

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

  1. Read an integer n from the user.
  2. Initialize a counter variable c to 0.
  3. Use a while loop that runs as long as n > 0.
  4. Inside the loop, divide n by 10 (n = n / 10) to strip off the last digit.
  5. Increment the counter c by 1.
  6. 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 n is 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 > 0 immediately fails, and it reports 0 digits instead of 1.
  • Running into an infinite loop by using a double instead of an integer for n.
ADVERTISEMENT