Digit Frequency in C – Hacker Rank Solution

Digit Frequency in C - Hacker Rank Solution
Digit Frequency in C – Hacker Rank Solution

Problem 

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 


Digit Frequency in C – Hacker Rank Solution

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

int main()
{
  
    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%s", s);
    s = realloc(s, strlen(s) + 1);
    int len = strlen(s), i;
    int arr[10];
    for(i = 0; i < 10; i++)
        arr[i] = 0;
    for(i = 0; i < len; i++) {
        if(s[i] >= '0' && s[i] <= '9') {
            arr[(int)(s[i] - '0')]++;
        }
    }
    for(i = 0; i < 10; i++)
        printf("%d ", arr[i]);
    printf("\n");
    free(s);
    return 0;
}

Disclaimer: The above Problem (Digit Frequency in C ) is generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.

Leave a Comment

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