Count number of digits in a given integer

To count the number of digits in a number we have to divide that number by 10 until it becomes 0 or less than 0. If you divide any number by 10 and store the result in an integer then it strips the last digit. So we have to apply the same logic here also.

Logic

After taking the input from the user, run one while loop that runs until the user given number becomes 0. Inside the loop for each iteration increase the counter variable by one and divide the user given number by 10 and store it in the same variable again.

Notice here we are using /= operator that performs division and stores the result in the same variable again.

Once the loop is over we have to print counter variable “count” containing the total number of digits.

Program

import java.util.Scanner;

public class CountDigits {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int num, temp;
        int count = 0;

        // Take input from user
        System.out.print("Enter any number : ");
        num = scanner.nextInt();

        // Store to temporary variable.
        temp = num;

        while(temp != 0) {

            // Increment counter
            count++;

            // Remove last digit of 'temp'
            temp /= 10;
        }

        System.out.println("\nTotal digits in " + num + " : "  + count);
    }

}

Output

Enter any number : 123456
Total digits in 123456 : 6