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)<=1000All 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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //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 whole problem statement is given by hackerrank.com but the solution is generated by the codeworld19 authority if any of the query regarding this post or website fill the following contact form thank you.
no need to typecast in line 19
We can also do like this
char s[1000];
scanf("%s", s);
int arr[10] = {0};
for(int i = 0; i='0' && s[i]<='9'){
arr[s[i]-'0']++;
}
}
for(int i = 0; i<10; i++){
printf("%d ", arr[i]);
}
Even I did the same like you, without dynamic memory allocation but still it won't work for me. 4/10 test cases still failed(no basic test cases included in it). Please reply me if you get answer of its why.
Sometimes you get an error if your code exceeds the time limit, this might happen when you use large bits of memory.
This comment has been removed by the author.
I wrote this code but why it ain't working for test case 0, can somebody pls explain, 2 testcases passed but one failed, it failed for the one string which had more than 20 elements in it.
#include
#define M 50
int main() {
char s[M],s1[M];
scanf("%[^\n]",s);
int i,t,k=0,rem,seen[10]={0};
int len=strlen(s);
for(i=0;i=1){
seen[rem]++;
}
else{
seen[rem]=1;
}
n=n/10;
}
for(i=0;i<10;i++){
printf("%d ",seen[i]);
}
return 0;
}