JAVA PROGRAM TO COUNT THE NUMBER OF DIGITS PRESENT IN A NUMBER

Category: Java program coding interview questions on numbers

Let, Given number be n , count the number of digits present in this number

Example :

Input n= 9876

Output: 4

There are 4 digits in 9876 , which are 9 , 8 , 7 & 6.

Approach :

In this approach count the digits by removing the digits from the given number starting from right to left till the number is reduced to 0 . Here remove digits from right because rightmost digit can be removed by performing integer division by 10 . For eg : n=9876, then 9876/10 = 987.6=987(Integer Division ) .

import java.util.*;

public class CountDigits {

public static void main (String args[] ) {

Scanner sc = new Scanner ( System.in) ;

System.out.println(“Enter the number to count the digits in it”);

int num=sc.nextInt();

int temp=num,count=0;

// if the number is exactly 0 , it has 1 digit

if(temp==0) {

count=1 ;

} else {

//Loop runs until the number become 0

while (temp >0 ) {

temp=temp/10; //Removes the last digit

count++;

}

}

System.out.println(“Number of digits : ” + count);

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *