Find the most frequent digit without using array/string - GeeksforGeeks
Given an integer, find the most occurring digit in it. If two or more digits occur same number of times, then return the highest of them. Input integer is given as an int variable, not as a string or array. Use of hash or array or string is not allowed.
Read full article from Find the most frequent digit without using array/string - GeeksforGeeks
Given an integer, find the most occurring digit in it. If two or more digits occur same number of times, then return the highest of them. Input integer is given as an int variable, not as a string or array. Use of hash or array or string is not allowed.
We could create a map of size 10 and store count of all digits, but use of any array/string is not allowed.
The idea is simple, we write a function that counts occurrences of a given digit in a given integer. Then we count all digits from 0 to 9 in given integer. We keep updating maximum count whenever count becomes more or same as previous count.
// Simple function to count occurrences of digit d in xint countOccurrences(long int x, int d){ int count = 0; // Initialize count of digit d while (x) { // Increment count if current digit is same as d if (x%10 == d) count++; x = x/10; } return count;}// Returns the max occurring digit in xint maxOccurring(long int x){ // Handle negative number if (x < 0) x = -x; int result = 0; // Initialize result which is a digit int max_count = 1; // Initialize count of result // Traverse through all digits for (int d=0; d<=9; d++) { // Count occurrences of current digit int count = countOccurrences(x, d); // Update max_count and result if needed if (count >= max_count) { max_count = count; result = d; } } return result;}