Find the frequency of a digit in a number using C++.


Here we will see how to get the frequency of a digit in a number. Suppose a number is like 12452321, the digit D = 2, then the frequency is 3.

To solve this problem, we take the last digit from the number, then check whether this is equal to d or not, if so then increase the counter, then reduce the number by dividing the number by 10. This process will be continued until the number is exhausted.

Example

 Live Demo

#include<iostream>
using namespace std;
int countDigitInNum(long long number, int d) {
   int count = 0;
   while(number){
      if((number % 10) == d)
         count++;
      number /= 10;
   }
   return count;
}
int main () {
   long long num = 12452321;
   int d = 2;
   cout << "Frequency of " << 2 << " in " << num << " is: " << countDigitInNum(num, d);
}

Output

Frequency of 2 in 12452321 is: 3

Updated on: 30-Oct-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements