Finding Number of Digits in a Number
The following Java program finds the number of digits in a number. This program converts the number to a string and then prints its length,
public class DigitsInNumber {
public static void main(String[] args ) {
int number = 94487;
String s = String.valueOf(number);
System.out.println(number + " has "+ s.length()+" digits");
}
}
The following is an alternate Java implementation which finds number of digits in a number without converting it into a string. This program divides the number by 10 until the number becomes 0. The number of iterations is equal to the number of digits.
public class DigitsInNumber {
public static void main(String[] args ) {
int original_number = 1119;
int n = original_number;
int digits = 0;
while(n > 0 ) {
digits ++;
n = n / 10;
}
System.out.println(original_number + " has "+ digits+" digits");
}
}