Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Count the Number of Digits in an Integer

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));
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading