Open In App

Count the number of occurrences of a particular digit in a number

Given a number N and a digit D, the task is to count the occurrences of D in N.
Examples: 

Input: N = 25, D = 2
Output: 1

Input: N = 100, D = 0
Output: 2

Naive Approach:



The basic idea is to loop through the digits of the number and keep a count of the occurrences of each digit in a hash table. Then, we can simply look up the count of the digit we are interested in.

Here are the steps in more detail:



Implementation of the above approach:




#include <bits/stdc++.h>
using namespace std;
 
int countOccurrences(long long int n, int d)
{
    // Initialize hash table with keys 0 to 9 and values 0
    unordered_map<int, int> digitCounts;
    for (int i = 0; i <= 9; i++) {
        digitCounts[i] = 0;
    }
     
    // Convert number to string and loop through its digits
    string numString = to_string(n);
    for (int i = 0; i < numString.length(); i++) {
        int digit = numString[i] - '0';
        digitCounts[digit]++;
    }
     
    // Return count for the digit we are interested in
    return digitCounts[d];
}
 
int main()
{
    int d = 2;
    long long int n = 214215421;
 
    cout << countOccurrences(n, d) << endl;
 
    return 0;
}




import java.util.HashMap;
 
public class Main {
    public static int countOccurrences(long n, int d) {
        // Initialize hash map with keys 0 to 9 and values 0
        HashMap<Integer, Integer> digitCounts = new HashMap<>();
        for (int i = 0; i <= 9; i++) {
            digitCounts.put(i, 0);
        }
         
        // Convert number to string and loop through its digits
        String numString = Long.toString(n);
        for (int i = 0; i < numString.length(); i++) {
            int digit = Character.getNumericValue(numString.charAt(i));
            digitCounts.put(digit, digitCounts.get(digit) + 1);
        }
         
        // Return count for the digit we are interested in
        return digitCounts.get(d);
    }
 
    public static void main(String[] args) {
        int d = 2;
        long n = 214215421;
 
        System.out.println(countOccurrences(n, d));
    }
}
 
// Contributed by sdeadityasharma




def countOccurrences(n, d):
    # Initialize dictionary with keys 0 to 9 and values 0
    digitCounts = {i: 0 for i in range(10)}
 
    # Convert number to string and loop through its digits
    numString = str(n)
    for digit in numString:
        digitCounts[int(digit)] += 1
 
    # Return count for the digit we are interested in
    return digitCounts[d]
 
if __name__ == "__main__":
    d = 2
    n = 214215421
 
    print(countOccurrences(n, d))
# This code is contributed by Prajwal Kandekar




// Javascript Program for the above approach
 
function countOccurrences(n, d) {
  // Initialize object with keys 0 to 9 and values 0
  let digitCounts = {};
  for (let i = 0; i < 10; i++) {
    digitCounts[i] = 0;
  }
 
  // Convert number to string and loop through its digits
  let numString = n.toString();
  for (let i = 0; i < numString.length; i++) {
    digitCounts[parseInt(numString.charAt(i))] += 1;
  }
 
  // Return count for the digit we are interested in
  return digitCounts[d];
}
 
// Driver Code
let d = 2;
let n = 214215421;
console.log(countOccurrences(n, d));
 
 
// This code is contributed princekumaras




using System;
using System.Collections.Generic;
 
class MainClass {
  static int CountOccurrences(long n, int d) {
    // Initialize dictionary with keys 0 to 9 and values 0
    Dictionary<int, int> digitCounts = new Dictionary<int, int>();
    for (int i = 0; i <= 9; i++) {
      digitCounts[i] = 0;
    }
 
    // Convert number to string and loop through its digits
    string numString = n.ToString();
    for (int i = 0; i < numString.Length; i++) {
      int digit = numString[i] - '0';
      digitCounts[digit]++;
    }
 
    // Return count for the digit we are interested in
    return digitCounts[d];
  }
 
  static void Main() {
    int d = 2;
    long n = 214215421;
 
    Console.WriteLine(CountOccurrences(n, d));
  }
}
// This code is contributed by user_dtewbxkn77n

Output
3

Time Complexity: O(n)
Auxiliary Space: O(n)

Approach: Take out the digits one by one in N and check if this digit is equal to D. If equal, then increment the count by 1. In the end, print the count.
Below is the implementation of the above approach: 
 




// C++ program to count the number of occurrences
// of a particular digit in a number
 
#include <iostream>
using namespace std;
 
// Function to count the occurrences
// of the digit D in N
long long int countoccurrences(long long int n,
                               int d)
{
    long long int count = 0;
 
    // Loop to find the digits of N
    while (n > 0) {
 
        // check if the digit is D
        count = (n % 10 == d)
                    ? count + 1
                    : count;
        n = n / 10;
    }
 
    // return the count of the
    // occurrences of D in N
    return count;
}
 
// Driver code
int main()
{
 
    int d = 2;
    long long int n = 214215421;
 
    cout << countOccurrences(n, d)
         << endl;
 
    return 0;
}




// Java program to count the number of occurrences
// of a particular digit in a number
import java.util.*;
 
class GFG
{
 
// Function to count the occurrences
// of the digit D in N
static int countoccurrences(int n,
                            int d)
{
    int count = 0;
 
    // Loop to find the digits of N
    while (n > 0)
    {
 
        // check if the digit is D
        count = (n % 10 == d) ?
                    count + 1 : count;
        n = n / 10;
    }
 
    // return the count of the
    // occurrences of D in N
    return count;
}
 
// Driver code
public static void main(String args[])
{
    int d = 2;
    int n = 214215421;
 
    System.out.println(countOccurrences(n, d));
}
}
 
// This code is contributed by Surendra_Gangwar




# Python3 program to count the
# number of occurrences of a
# particular digit in a number
 
# Function to count the occurrences
# of the digit D in N
def countoccurrences(n, d):
    count = 0
 
    # Loop to find the digits of N
    while (n > 0):
 
        # check if the digit is D
        if(n % 10 == d):
            count = count + 1
  
        n = n // 10
 
    # return the count of the
    # occurrences of D in N
    return count
 
# Driver code
d = 2
n = 214215421
print(countOccurrences(n, d))
 
# This code is contributed by Mohit Kumar




// C# program to count the number
// of occurrences of a particular
// digit in a number
using System;
class GFG
{
 
// Function to count the occurrences
// of the digit D in N
static int countoccurrences(int n,
                            int d)
{
    int count = 0;
 
    // Loop to find the digits of N
    while (n > 0)
    {
 
        // check if the digit is D
        count = (n % 10 == d) ?
                    count + 1 : count;
        n = n / 10;
    }
 
    // return the count of the
    // occurrences of D in N
    return count;
}
 
// Driver code
public static void Main()
{
    int d = 2;
    int n = 214215421;
 
    Console.WriteLine(countOccurrences(n, d));
}
}
 
// This code is contributed by Code_Mech.




<script>
 
// Javascript program to count
// the number of occurrences
// of a particular digit in a number
 
// Function to count the occurrences
// of the digit D in N
function countoccurrences(n, d)
{
    let count = 0;
 
    // Loop to find the digits of N
    while (n > 0) {
 
        // check if the digit is D
        count = (n % 10 == d)
                    ? count + 1
                    : count;
        n = parseInt(n / 10);
    }
 
    // return the count of the
    // occurrences of D in N
    return count;
}
 
// Driver code
 
    let d = 2;
    let n = 214215421;
 
    document.write(countOccurrences(n, d));
 
</script>

Time Complexity : O(log(n)), where n is the input variable
Auxiliary Space : O(1)


Article Tags :