I cracked this recently in hackerrank and all the tests passed. So, I wanted to record this, and this is the most frequently asked question in interviews. Here, I also mentioned another important trick of converting the string to integer without using any library functions.
How to convert string to an integer? or conversion of char[] to int[] ?
if (num[i] >= '0' && num[i] <= '9') {
//printf("DEBUG: index %d num %c value %d\n", i, num[i], (num[i] - '0'));
result[i] = (num[i] - '0');
//printf("DEBUG: index %d num %c value %d\n", i, num[i], (num[i] - '0'));
result[i] = (num[i] - '0');
//printf("DEBUG: result %d\n", result[i]);
}
}
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX_SIZE 1000
#define TOTAL_DIGITS 10
int main() {
char num[MAX_SIZE] = {'\0'};
int len, i = 0;
long int index = 0;
int result[TOTAL_DIGITS] = {0};
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
scanf("%s", num);
len = strlen(num);
//printf("\nThe frequency for the string to be found is %s length %d\n", num, len);
for (i = 0; i < len; i++) {
/* Requirement is to find frequency of only digits,
so skipping the alphabets */
if (num[i] >= '0' && num[i] <= '9') {
//printf("DEBUG: index %d num %c value %d\n", i, num[i], (num[i] - '0'));
result[(num[i] - '0')]++;
/* If you are uncommenting the below line, remove the above line. */
//printf("DEBUG: result %d\n", result[(num[i] - '0')]++);
}
}
for (i = 0; i < TOTAL_DIGITS; i++) {
printf("%d ", result[i]);
}
return 0;
}
Comments
Post a Comment