Saturday, 8 July 2017

Java Code to counts the number of digits in an integer

Problem:

Design an algorithm that counts the number of digits in an integer.

Solution:

package com.myprograms;

import java.util.Scanner;

public class CountNoOfDigits {

public static void main(String[] args) {
System.out.println("the number of digits in given number " + countDigits(getTheNumber()));
}

public static int getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
int n = s.nextInt();
s.close();
return n;
}

private static int countDigits(int n){
int count = 0;
while(n > 0){
if((n % 10) > -1){
count = count + 1;
}
n = n/10;
}
return count;
}
}


Output:

enter the n value
287390
the number of digits in given number 6



No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...