Java program to count number of digits in an integer
Here you can learn how to find the total number of digits in an given integer using java programming language with 2 different approaches.
Approach :-1 "count number of digits in an integer in java"
import java.util.Scanner;
public class usingForLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = sc.nextInt();
int digit = 0;
for(int i = 0; i <= num; ++i){
num = num / 10;
digit++;
}
System.out.println("The total digits are: "+digit);
}
}
Output
Approach :-2 "count number of digits in an integer in java"
import java.util.Scanner;
public class usingWhileLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = sc.nextInt();
int digit = 0;
while(num != 0){
num = num / 10;
digit++;
}
System.out.println("The total number of digits are: "+ digit);
}
}
Code Explanation
Here I will properly explain how these two approaches are working.
Approach :-1
- We just need to count the number of digits in an integer. If you divide any number with 10 the results will the delete the last digit.
Ex :- if a number is 123 when we divide it with 10, here 3 will remove and the results will be 12.
- In side loop I am repeatedly removing one by one from the last. See if the number contain 3 digits, it will iterate the loop 3 times.
- Now easily we can determine the number of digits in an integer.
Approach:-2
- Here I have used while loop and the whole condition will remain same.
- If you learn something new from this article please share with your friends.
- And if you have any query please write it on the comment below 👇.