Find the most frequent digit without using array/string












Find the most frequent digit without using array/string

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.

Example:

Input:  x = 12234
Output: The most frequent digit is 2

Input:  x = 1223377
Output: The most frequent digit is 7

Input:  x = 5
Output: The most frequent digit is 5

Input:  x = 1000
Output: The most frequent digit is 0


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. Below is the implementation.

// Finds maximum occurring digit without using any array/string
#include <bits/stdc++.h>
using namespace std;
  
// Simple function to count occurrences of digit d in x
int 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 x
int 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;
}
  
// Driver program
int main()
{
    long int x = 1223355;
    cout << "Max occurring digit is " << maxOccurring(x);
    return 0;
}


Output:

Max occurring digit is 5

























































































 

Comments

Popular posts from this blog

Kth most frequent Character in a given String

[16 Feb 2020] Given an array where every element occurs three times, except one element which occurs only once.

[17 Feb 2020] Given an array of integers, find the nearest smaller number for every element such that the smaller element is on left side.