Search code examples
javadigits

A quicker method for finding out the number of digits in a number and print it?


I have a question given by my computer teacher to find out the number of two digit number and three digit number and terminate the program (when user enter 0 )and print the total two digit ,three digit numbers and other digit number.

This is an example output in terminal window:

Enter your number: 23
Enter your number: 1
Enter your number: 412
Enter your number: -123
Enter your number: 32332
Enter your number: 12
Enter your number: -1
Enter your number: 0
Two digit numbers : 2
Three digit numbers : 2
Other digit numbers : 3

This is my program :

import java.io.*;
public class two_three_digits
{
    static DataInputStream dis = new DataInputStream(System.in);
    static void main()throws IOException
    {
        int two = 0 , three = 0 , oth = 0;
        while(true)
        {
            System.out.print("Enter your number: ");
            int n = Integer.parseInt(dis.readLine());
            n = (int)Math.abs(n);
            int d = 0,cn = n;
            if(n == 0)break;
            else if(n > 9 && n < 100)two++;
            else if(n > 99 && n <1000)three++;
            else oth++;
        }
        System.out.println("Two digit numbers : "+two);
        System.out.println("Three digit numbers : "+three);
        System.out.println("Other digit numbers : "+oth);
    }
}

I wished to know if there was any shorter way to do the same task ? Like using arrays , string or Bitswise operator , etc. Also I would rather like if you would tell the method of how to do it instead of simply the program as I am a learning student and wish to solve it out myself.

Edit: Sorry because i forgot to term one thing - by the word quicker i actually meant for speed (and more or less , size of program too)


Solution

  • Building on the idea of using log10 to determine the number of digits, use an array to store the number of numbers with a certain number of digits.

    public static void main(final String[] args) throws InterruptedException {
        int[] digits = new int[3];
        final Console c = System.console();
        while (true) {
            final int n = Math.abs(Integer.parseInt(c.readLine("Enter your number: ")));
            if (n == 0) {
                break;
            }
            digits[(int) Math.floor(Math.log10(n))]++;
        }
        System.out.println(Arrays.toString(digits));
    }
    

    Obviously if the user enters a number with more than three digits, the program will crash - so if you want to support that you could add bounds checks.

    If by "quicker" you means "easier" then this solution certainly has fewer lines...