Find the frequency of a digit in a number
Last Updated :
13 Mar, 2023
Given a number N and a digit D. Write a program to find how many times the digit D appears in the number N.
Examples :
Input: N = 1122322 , D = 2
Output: 4
Input: N = 346488 , D = 9
Output: 0
The idea to solve this problem is to keep extracting digits from the number N and check the extracted digits with the given digit D. If the extracted digit is equals to the digit D then increment the count.
Below is the implementation of above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int frequencyDigits( int n, int d)
{
int c = 0;
while (n > 0) {
if (n % 10 == d)
c++;
n = n / 10;
}
return c;
}
int main()
{
int N = 1122322;
int D = 2;
cout<<frequencyDigits(N,D);
return 0;
}
|
Java
class GFG
{
static int frequencyDigits( int n,
int d)
{
int c = 0 ;
while (n > 0 )
{
if (n % 10 == d)
c++;
n = n / 10 ;
}
return c;
}
public static void main(String args[])
{
int N = 1122322 ;
int D = 2 ;
System.out.println(frequencyDigits(N, D));
}
}
|
Python3
def frequencyDigits(n, d):
c = 0 ;
while (n > 0 ):
if (n % 10 = = d):
c + = 1 ;
n = int (n / 10 );
return c;
N = 1122322 ;
D = 2 ;
print (frequencyDigits(N, D));
|
C#
using System;
class GFG
{
static int frequencyDigits( int n,
int d)
{
int c = 0;
while (n > 0)
{
if (n % 10 == d)
c++;
n = n / 10;
}
return c;
}
static public void Main(String []args)
{
int N = 1122322;
int D = 2;
Console.WriteLine(frequencyDigits(N, D));
}
}
|
PHP
<?php
function frequencyDigits( $n , $d )
{
$c = 0;
while ( $n > 0)
{
if ( $n % 10 == $d )
$c ++;
$n = $n / 10;
}
return $c ;
}
$N = 1122322;
$D = 2;
echo frequencyDigits( $N , $D );
?>
|
Javascript
<script>
function frequencyDigits(n, d)
{
var c = 0;
while (n > 0)
{
if (n % 10 == d)
c++;
n = parseInt(n / 10);
}
return c;
}
var N = 1122322;
var D = 2;
document.write(frequencyDigits(N, D));
</script>
|
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...