This is a sample code to Count the Number of Digits in an Integer with java
class CountDigits {
private static int countDigits(int n){
return n != 0 ? ((int) Math.floor(Math.log10(n) + 1)) : -1;
}
public static void main(String[] args) {
int number = 125;
System.out.println("Number of digits : " + countDigits(number));
}
}
my ask to explain this line
return n != 0 ? ((int) Math.floor(Math.log10(n) + 1)) : -1;
and why using ? and :
Thanks
>Solution :
The integer part of log10 gives a measure of the number of digit in a number.
For example log10(1000) is 3 and log10(10000) is 4.
So adding 1 to the integer part gives the number of decimal digits.
However log10(0) is undefined and would raise a run time error. The phrase
n != 0 ? expr1 : expr2
ensures that expr1 is not evaluated if n is 0