Q. Java Program to Count the Number of Digits in a Number.


Here you will find an algorithm and program in Java programming language to count number of digits in a number. First let us understand this.

Explanation : Suppose an input number is given as 12341 then the output will be 5 as there are 5 digits in the given number and digits are 1, 2, 3, 4, 1.

Algorithm to count the number of digits in a given number

START
step 1 : Input a number from user. Store it in some variable say num.
step 2 : Initialize another variable to store total digits say digit = 0.
step 3 : If num > 0 then increment count by 1 i.e. count++.
step 4 : Divide num by 10 to remove last digit of the given number i.e. num = num / 10.
step 5 : Repeat step 3 to 4 till num > 0 or num != 0.
STOP


Java Program to Count Number of Digits in a Number

class LFC { 
	static int count_digit(long num) 
	{ 
		int count = 0; 
		while (num != 0) { 
			num = num / 10; 
			++count; 
		} 
		return count; 
	} 

	public static void main(String[] args) 
	{ 
		long num = 874512369; 
		System.out.print("Number of digits : " + count_digit(num)); 
	} 
} 

Output

Number of digits : 9