Count Digits in a Number in Java
Problem
Counting a number's digits means counting how many times it can be divided by 10 before nothing is left — each division strips off exactly one digit.
Given a number, find how many digits it has.
Java Program
public class CountDigits {
public static void main(String[] args) {
int n = 45678;
if (n == 0) { // 0 has one digit, but the loop below would never run for it
System.out.println("Number of digits: 1");
return;
}
int count = 0;
while (n != 0) {
n /= 10;
count++;
}
System.out.println("Number of digits: " + count);
}
}Output
Core Logic
Dividing the number by 10 repeatedly, and counting each division, tallies the digit count directly — the loop stops exactly when nothing is left to divide.
- 1
n == 0is handled as a special case up front, since0is a single digit but the division loop would otherwise never run for it. - 2The loop divides
nby10on each pass, discarding the digit that fell off. - 3
countincrements once per division, tracking how many digits have been stripped away. - 4The loop continues until
nreaches0, at which point every digit has been counted.
45678, five divisions are needed to bring it down to 0, so count ends at 5.Key Point: The n == 0 special case matters because 0 genuinely has one digit, but the loop's own condition (n != 0) would otherwise skip it entirely and report zero digits.
Why: The loop divides n by 10 once per digit, so the number of iterations equals n's digit count d, with only a running counter kept.
Key Concepts
Approach 2: Using String Length
public class CountDigitsStringLength {
public static void main(String[] args) {
int n = 45678;
// The string form's length is exactly the digit count
int count = String.valueOf(n).length();
System.out.println("Number of digits: " + count);
}
}
Output
Core Logic
Converting the number to a String and asking for its length reports the digit count directly, without a manual division loop.
- 1
String.valueOf(n)converts the number into its digit string. - 2
.length()returns how many characters that string contains, which is exactly the digit count. - 3The
n == 0case needs no special handling here —String.valueOf(0)is already the one-character string"0".
45678, String.valueOf(45678) is "45678", and .length() reports 5.Key Point: Building the digit string still costs work proportional to the digit count, so this isn't free — it just moves that cost into the String conversion instead of a visible loop.
Why: Converting the number to a String still does work proportional to its digit count d, and the resulting String itself takes space proportional to d.