This problem is pretty common in interviews and computer examinations.
Candidate is required to write a program where a user enters any random integer and the program should display the digits and their frequency in the number.
For Example, if the entered number is 74526429492, then frequency of 7 is 1, 4 is 3, 5 is 1, 6 is 1, 2 is 3, 9 is 2.
In tabular format,
Number | Frequency |
7 | 1 |
4 | 3 |
5 | 1 |
6 | 1 |
2 | 3 |
9 | 2 |
There can be many ways to program the above problem. This article will explain two ways to find frequency of each digit in a number with explanation and output
Method 1: Using array
Initialize an array of size 10 whose each location represents a digit from 0 to 9. Value at a location of the array is the count(or frequency of occurrence) of that digit.
That is, a value of 2 at index 5 means that 5 occurs 2 times in the number.
Extract the digits of the number by taking modulus of the number by 10. Increment the count at location corresponding to the digit extracted.
Thus, if the digit is 2, then increment the value at 2nd position of the array, if the digit is 8, then increment the value at 8th position of the array and so on.
Continue this till all the digits of the array have been covered.
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number"); int number = scanner.nextInt(); // initialize array to hold count of digits int[] digitArray = new int[10]; int remainder = 0; // loop to get digits of the number while (number > 0) { // get the last digit remainder = number % 10; // increment the count of this digit digitArray[remainder]++; // remove the last digit from the number number = number / 10; } System.out.println("-------------------------"); System.out.println("Number\tFrequency"); System.out.println("-------------------------"); // iterate over the digit array. // Each count represents a digit from 0 to 9 for (int counter = 0; counter < digitArray.length; counter++) { // get the count int digitCount = digitArray[counter]; if (digitCount != 0) { System.out.println(counter + "\t" + digitCount); } } scanner.close(); }
Output
Enter the number
2345342
———————
Number Frequency
———————
2 2
3 2
4 2
5 1
Method 2: Using java.util.Map
Initialize a java.util.Map
which will hold the digit as a key and its frequency of occurrence in the number as value.
As in the above example, each digit is extracted and every time it is put as a key, the value corresponding to the key is incremented.
In order the print the digits and their frequency count, the map is iterated.
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number"); int number = scanner.nextInt(); // initialize map to hold digits and their count Map<Integer, Integer> digitMap = new HashMap<Integer, Integer>(); int remainder = 0; // loop to get digits of the number while (number > 0) { // get the last digit remainder = number % 10; // get the frequency count of this digit Integer count = digitMap.get(remainder); // for the first time count will be null, hence put 1 if (count == null) { digitMap.put(remainder, 1); } else { // increment the count for this digit digitMap.put(remainder, ++count); } // remove the last digit from the number number = number / 10; } System.out.println("-------------------------"); System.out.println("Number\tFrequency"); System.out.println("-------------------------"); Iterator iterator = digitMap.keySet().iterator(); while (iterator.hasNext()) { int digit = iterator.next(); int digitCount = digitMap.get(digit); System.out.println(digit + "\t" + digitCount); } scanner.close(); }
Output
Enter the number
2345342
————————-
Number Frequency
————————-
2 2
3 2
4 2
5 1
Method 3: Using a Loop
One of the most efficient ways to find the frequency of digits in a number is by using a single loop.
This method eliminates the need for additional data structures like HashMap or arrays, making it a more memory-efficient solution.
In this approach, we will iterate through each digit of the number using a while loop.
For each iteration, extract the last digit of the number using the modulus operator (%), increment the corresponding frequency counter, and then remove the last digit from the number using integer division (/).
This process is repeated until the number becomes 0.
Below is the code example
public class Main { public static void main(String[] args) { int num = 12341234; int[] freq = new int[10]; while (num!= 0) { int digit = num % 10; freq[digit]++; num /= 10; } System.out.println("-------------------------"); System.out.println("Number\tFrequency"); System.out.println("-------------------------"); for (int i = 0; i < 10; i++) { if(freq[i]!=0) System.out.println(i + "\t" + freq[i]); } } }
In this code, we create an array to store the frequency of each digit from 0 to 9.
We then use a while loop to iterate through each digit of the number, incrementing the corresponding frequency counter and removing the last digit from the number.
Finally, we print out the frequency of each digit using a for loop.
This method is not only efficient in terms of memory usage but also provides a simple and straightforward solution to the problem.
By using a single loop, you can easily find the frequency of digits in a number without having to worry about complex data structures or recursive function calls.
Method 4: Using Recursion
When a method calls itself, it is called Recursion and it can also be used to find the frequency of digits in a number.
In this method, we will create a recursive function that takes an integer as an argument and returns an array of frequencies for each digit.
Here’s an example of how you can implement this method: java
public class Main { public static void main(String[] args) { int num = 123456; // array to store frequencies of digits 0-9 int[] freq = new int[10]; // call recursive method findDigitFrequencies(num, freq); System.out.println("-------------------------"); System.out.println("Number\tFrequency"); System.out.println("-------------------------"); for (int i = 0; i < 10; i++) { if(freq[i]!=0) System.out.println(i + "\t" + freq[i]); } } public static void findDigitFrequencies(int num, int[] freq) { if (num == 0) { return; } int digit = num % 10; freq[digit]++; findDigitFrequencies(num / 10, freq); } }
In this code, findDigitFrequencies()
method takes an integer num
and an array freq
as arguments.
It extracts the last digit of num
using the modulo operator (`%`), increments the corresponding frequency in the freq
array, and then recursively calls itself with num
divided by 10 (imperatively removing the last digit).
This process continues until num
becomes 0, at which point the recursion stops.
Method 5: Using Java 8 Streams
Java 8 Streams can also be used to find frequency of digits in a number.
In this approach, we will use the IntStream
class to generate a stream of digits from the input number.
Then, we will use the collect()
method to group the digits by their values and count their frequencies using a Map
.
Below is the code example
import java.util.Map; import java.util.stream.Collectors; public class DigitFrequency { public static void main(String[] args) { int number = 1234512345; Map<Integer, Long> digitFrequencies = String. valueOf(number). chars(). map(c -> c - '0'). boxed(). collect(Collectors.groupingByConcurrent(i -> i, Collectors.counting())); digitFrequencies.forEach((digit, frequency) -> System.out.println("Digit " + digit + " appears " + frequency + " times")); } }
In this code, we first convert the input number to a string and then use the chars()
method to generate a stream of characters (i.e., digits).
We then map each character to its corresponding integer value by subtracting the ASCII value of ‘0’ from it.
Finally, you use the collect()
method to group the digits by their values and count their frequencies using a Map
.
The resulting map contains the digit frequencies, which you can then iterate over to print the results.
This approach is concise and efficient, taking advantage of the parallel processing capabilities of Java 8 Streams.
By using the groupingByConcurrent()
collector, we can take advantage of multi-core processors to speed up the computation.
Method 6: Using StringBuilder
In this method, we will convert the input number into a string and then use a StringBuilder
to iterate over each character (digit) in the string.
We maintain a count of each digit using an array, where the index represents the digit (0-9) and the value at that index represents the frequency of that digit.
Below is the code example that demonstrates this approach
public class DigitFrequencyStringBuilder { public static void main(String[] args) { int num = 1234567890; int[] freq = new int[10]; StringBuilder sb = new StringBuilder(String.valueOf(num)); for (int i = 0; i < sb.length(); i++) { freq[sb.charAt(i) - '0']++; } for (int i = 0; i < 10; i++) { System.out.println("Frequency of " + i + ": " + freq[i]); } } }
In this code, we first convert the input number into a string using the String.valueOf()
method.
Then, we create a StringBuilder
object from this string. charAt()
method is used to iterate over each character in the StringBuilder
, and the frequency of each digit is incremented in the freq
array.
Finally, we print out the frequency of each digit using a loop that iterates over the freq
array.
This approach is simple and efficient, making it a viable option for finding digit frequencies in a number.
Conclusion
You now have a comprehensive understanding of the various methods to find the frequency of digits in a number in Java.
Hope this post was helpful.