Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

problem in comparing string to a integer i guess

This code is not working, how many times the number 0 to 9 is repeated in a given string.

This is the question, itis from hackerrank:

Given a string, S, consisting of alphabets and digits, find the frequency of each digit in the given string.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can’t find any error in my logic.

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

int main()
{
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    char s[1000];
    int count[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    char temp;
    scanf("%s", s);

    for (int i = 0; i < 10; i++)
    {
        temp = i;

        for (int j = 0; j < strlen(s); j++)
        {
            if (s[j] == i)
            {
                count[i] = count[i] + 1;
                continue;
            }
            else
            {
                continue;
            }
        }
    }

    for (int k = 0; k < 10; k++)
    {
        printf("%d ", count[k]);
    }

    return 0;
}

>Solution :

At least you need to write

if (s[j] == i + '0')

Otherwise you are trying to compare a character like '0' that can have the ASCII code 48 with integer 0.

But in any case the for loops are inefficient.

It is better to write:

for (const char *p = s; *p; ++p)
{
    if ('0' <= *p && *p <= '9') ++count[*p - '0'];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading