22-10 HACKERRANK C PROGRAMMING - DIGIT FREQUENCY
SOLUTION
MY SOLUTION
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
char s[1000];
int arr[10] = {0};
scanf("%s", s);
int i, j, num;
for(i = 0;s[i] != '\0'; i++){
num = s[i]-'0';
// printf("%d\n", s[i]-'0');
if((num>=0) && (num<=9)){
// printf("%d ", num);
for(j = 0; j < 10; j++){
if(num == j){
arr[j]++;
}
}
}
}
for(i=0; i < 10; i++){
printf("%d ", arr[i]);
}
return 0;
}
DISCUSSION
int main() { int* nums = (int*) malloc(10 * sizeof(int)); char c; for(int i = 0; i < 10; i++) *(nums+i) = 0; while(scanf("%c", &c) == 1) if(c >= '0' && c <= '9') (*(nums+(c-'0')))++; for(int i = 0; i < 10; i++) printf("%d ", *(nums+i)); return EXIT_SUCCESS; }
PROBLEM SETTERS 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; }
No comments:
Post a Comment