public class DigitCounter {
/**
* Returns the number of digits in an integer.
*
* This approach converts the number to a String and uses its length.
* Modern JVMs optimize String operations very well, making this
* both clear and efficient for everyday use.
*
* Handles negative numbers by stripping the leading '-' sign.
*/
public static int countDigits(int value) {
// Convert the integer to a string representation
String text = String.valueOf(value);
// If the number is negative, ignore the '-' sign
if (text.charAt(0) == '-') {
return text.length() - 1;
}
// Otherwise, the length of the string is the digit count
return text.length();
}
public static void main(String[] args) {
// Example input
int number = 123456;
// Compute the digit count using our function
int digits = countDigits(number);
// Display the result
System.out.println("Number: " + number);
System.out.println("Digit count: " + digits);
}
}
/*
run:
Number: 123456
Digit count: 6
*/