Digit Frequency in C | HackerRank Solution

Hey coderz, today we will be solving Digit Frequency in C HackerRank Solution.

Digit Frequency in C HackerRank Solution

Objective

Given a string, s, consisting of alphabets and digits, find the frequency of each digit in the given string.

Input Format

The first line contains a string, num which is the given number.

Constraints

1 <= len(num) <= 1000

All the elements of num are made of english alphabets and digits.

Output Format

Print ten space-separated integers in a single line denoting the frequency of each digit from 0 to 9.

Sample Input 0

a11472o5t6

Sample Output 0

0 2 1 0 1 1 1 1 0 0 

Explanation 0

In the given string:

  • 1 occurs two times.
  • 2,4,5,6 and 7 occur one time each.
  • The remaining digits 0, 3, 8 and 9 don’t occur at all.

Sample Input 1

lw4n88j12n1

Sample Output 1

0 2 1 0 1 0 0 0 2 0 

Sample Input 2

1v88886l256338ar0ekk

Sample Output 2

1 1 1 2 0 1 2 0 5 0 

Solution – Digit Frequency in C HackerRank Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    char s;
    int i,a[] ={0,0,0,0,0,0,0,0,0,0};
    while(scanf("%c", &s) == 1)
        if(s >= '0' && s <= '9')
            a[s-'0']+=1;
                        
    for(i=0;i<10;i++)
        printf("%d ",a[i]);  
    return 0;
}
Digit Frequency in C HackerRank Solution
Digit Frequency in C HackerRank Solution

EXPLANATION

  • Declare an frequency array, arr of size 10 and initialize it with zeros, which will be used to count the frequencies of each of the digits occurring.
  • Given a string, s, iterate through each of the characters in the string. Check if the current character is a number or not.
  • If the current character is a number, increase the frequency of that position in the arr array by 1.
  • Once done with the iteration over the string, s, in a new line print all the 10 frequencies starting from 0 to 9, separated by spaces.

Disclaimer: The above Problem (Digit Frequency in C) is generated by Hacker Rank but the Solution is provided by CodingBroz.

Broz Who Code

CodingBroz

Leave a Comment

Your email address will not be published. Required fields are marked *