Answer
Count Number of Digits in a Number
Java
public class NumberOfDigits {
public static void main(String[] args) {
int count = 0;
int num = 3452;
while (num != 0) {
num /= 10; // 3452 → 345 → 34 → 3 → 0
++count; // increment digit count each iteration
}
System.out.println("Number of digits: " + count);
}
}
Output
CODE
Number of digits: 4
Step-by-Step Trace
CODE
num=3452, count=0
Iteration 1: num = 3452/10 = 345, count = 1
Iteration 2: num = 345/10 = 34, count = 2
Iteration 3: num = 34/10 = 3, count = 3
Iteration 4: num = 3/10 = 0, count = 4
Loop ends (num == 0)
Result: 4 digits
One-liner Using String Length
Java
int num = 3452;
int digits = String.valueOf(Math.abs(num)).length();
System.out.println("Digits: " + digits); // 4
Handle Negative Numbers
Java
public static int countDigits(int num) {
if (num == 0) return 1; // special case: 0 has 1 digit
num = Math.abs(num); // handle negatives: -345 → 345
int count = 0;
while (num != 0) {
num /= 10;
count++;
}
return count;
}
System.out.println(countDigits(0)); // 1
System.out.println(countDigits(12345)); // 5
System.out.println(countDigits(-999)); // 3
System.out.println(countDigits(1000000)); // 7
Using Math.log10() (Mathematical)
Java
int num = 3452;
int digits = (int) Math.log10(num) + 1;
System.out.println("Digits: " + digits); // 4
// log10(3452) ≈ 3.537 → (int)3.537 = 3 → 3+1 = 4
Automation Testing Relevance
Java
// Validate phone number digit count
String phone = driver.findElement(By.id("phone")).getAttribute("value");
int digitCount = phone.replaceAll("[^0-9]", "").length();
assertEquals(digitCount, 10, "Phone number must be 10 digits");
