Count Digits

Count the number of digits in a given integer.

JavaBeginner
Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();

        if (n == 0) {
            System.out.println("Digits = 1");
            return;
        }

        n = Math.abs(n);
        int count = 0;
        while (n != 0) {
            count++;
            n /= 10;
        }

        System.out.println("Digits = " + count);
        sc.close();
    }
}

Output

Enter a number: 12345
Digits = 5

We divide by 10 until the number becomes 0 and count iterations.