Thursday, 23 April 2015

Count total digits

import java.io.InputStreamReader;
import java.io.BufferedReader;

public class bCountDigits {
    public static void main(String args[]) {
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader reader = new BufferedReader(in);

        int num = 0;
        // get a number
        System.out.println("Enter a number : ");
        try {
            num = Integer.parseInt(reader.readLine());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Out of memory");
            return;
        }
        int temp = num;
        int ttlDigits = 0;
        while (num > 0) {
            ++ttlDigits;
            num /= 10;
        }

        ttlDigits = (ttlDigits == 0) ? 1 : ttlDigits;

        System.out.println("Total digits in " + temp + " is " + ttlDigits);

    }
}

No comments:

Post a Comment