Digit Frequency in C - Hacker Rank Solution

Hello coders, today we will be solving Digit Frequency in C Hacker Rank Solution. Given a string, s, consisting of alphabets and digits, find the freq

Hello coders, today we will be solving Digit Frequency in C Hacker Rank Solution.

Digit Frequency in C - Hacker Rank 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 - 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 Hacker Rank but the Solution is provided by Sloth Coders.

A Sloth Who Code

Sloth Coders

Also Read:

Sloth Coders is a Learning Platform for Coders, Programmers and Developers to learn from the basics to advance of Coding of different langauges(python, Java, Javascript and many more).

Post a Comment