Table of contents
By Loop
public static int countDigitsInt(int input) {
int count = 0;
while (input != 0) {
input /= 10;
++count;
}
return count;
}
By Math
System.out.println(((int) (Math.log10(input)) + 1));
By String method
System.out.println(Integer.toString(input).length());
speed
Loop > Math > String method
Explanation
Loop
divide the input by 10 until cannot. Then cound how many times divided
Math
Basic log definition is
$$A=B^x \iff x=\log_B A$$
Therefore, if you log 10 for integer 336 means
$$336=10^x \iff x=\log_{10} 336$$
Thus, log 10 for number will return Number of Digits - 1
String method
String have counting method which is "length()" convert integer to String and use the method.