Find the frequency of all digits in java
In this article you can learn how we can find out the frequency of each digits of an integer number using java.
I use my android phone to code this program using java android ide i.e java N-IDE. Please support.
Approach:-1 "Find the frequency of each digits of a number in java"
public class findFrequency {
public static void main(String[] args) {
int num = 22463234;
System.out.println("Digit : Frequency in "+num);
System.out.println(2 + " :---> "+ returnFrequency(num,2));
System.out.println(3 + " :---> "+ returnFrequency(num,3));
System.out.println(4 + " :---> "+ returnFrequency(num,4));
System.out.println(6 + " :---> "+ returnFrequency(num,6));
}
public static int returnFrequency(int num, int digit){
int count = 0;
while(num > 0){
int lastDigit = num % 10;
if(digit == lastDigit)
{
count++;
}
num = num / 10;
}
return count;
}
}
Frequency of digits in a number means the number of occurance of each digits in a integer number.
We can find the frequency by using modulus operator in java, how let's see. Modulus operator (%) with 10 i.e num % 10 will give the last digit of a number.
Now we will compare(using if statement) that last digit with individual digits of that number.
If both digits match, we simply increment a variable i.e count, which is initially created.
If a digit is present in a number in 3 places, then count will incremented 3 times. So we can easily say the frequency of a different digits.
Output
Hey if you have any questions or any doubt regarding programming, feel free to ask me in the comment below.
And yes if you learn something new from the article please share with your friends.