Java Program to Count Digits in Number
while (num != 0) { count++; num /= 10; }.Examples
How to Think About It
Algorithm
Code
public class DigitCount { public static void main(String[] args) { int num = 12345; int count = 0; int temp = num; if (temp == 0) { count = 1; } else { while (temp != 0) { count++; temp /= 10; } } System.out.println("Number of digits in " + num + " is: " + count); } }
Dry Run
Let's trace the number 12345 through the code to count its digits.
Initialize variables
num = 12345, count = 0, temp = 12345
Check if temp is 0
temp is 12345, so not 0, skip count=1
Start loop: temp != 0
count=0, temp=12345
First iteration
count=1, temp=12345/10=1234
Second iteration
count=2, temp=1234/10=123
Third iteration
count=3, temp=123/10=12
Fourth iteration
count=4, temp=12/10=1
Fifth iteration
count=5, temp=1/10=0
Loop ends
temp=0, exit loop
Print result
Number of digits in 12345 is: 5
| Iteration | count | temp |
|---|---|---|
| 1 | 1 | 1234 |
| 2 | 2 | 123 |
| 3 | 3 | 12 |
| 4 | 4 | 1 |
| 5 | 5 | 0 |
Why This Works
Step 1: Handle zero input
If the number is 0, it has exactly one digit, so we set count to 1 immediately.
Step 2: Divide to remove digits
Dividing the number by 10 removes its last digit, so each division counts one digit.
Step 3: Count divisions
We keep dividing and counting until the number becomes 0, which means all digits are counted.
Alternative Approaches
public class DigitCount { public static void main(String[] args) { int num = 12345; String str = Integer.toString(num); System.out.println("Number of digits in " + num + " is: " + str.length()); } }
public class DigitCount { public static void main(String[] args) { int num = 12345; int count = (num == 0) ? 1 : (int) Math.log10(num) + 1; System.out.println("Number of digits in " + num + " is: " + count); } }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit, so time grows linearly with the number of digits, O(d).
Space Complexity
Only a few variables are used, so space is constant, O(1).
Which Approach is Fastest?
The logarithm method is fastest for large numbers but less intuitive; the loop method is simple and reliable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop division | O(d) | O(1) | All integers, simple logic |
| String conversion | O(d) | O(d) | Quick coding, small numbers |
| Logarithm method | O(1) | O(1) | Fastest for large positive numbers |