dcsimg
 

Submitted by: M S Sridhar(sridhar.ms@gmail.com)

Monday Feb 25th 2019 by M S Sridhar

Language: Java, Expertise: Intermediate - Learn how to use a combination of methods in Math package to count digits.

A typical mechanism of converting to a string, traversing and counting has a lot of processing to complete.

Instead, the code below shows a combination of methods in Math package to help us achieve the same.

*/

public class DigitCount
{
   public static void main(String args[])
   {
      DigitCount digitCount = new DigitCount();
      digitCount.proceed();
   }
   
   private void proceed()
   {
      int aNumber = 56554;
      System.out.println("Digit count in " + aNumber + ": " + Math.round(Math.floor(Math.log10(aNumber)) + 1));
   }
}

/*

Expected output:

[root@mypc]# java DigitCount
Digit count in 56554: 5

*/ 
Home
Mobile Site | Full Site