Home > database >  problem in comparing string to a integer i guess
problem in comparing string to a integer i guess

Time:12-28

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.

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;
}

CodePudding user response:

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'];
}

CodePudding user response:

You are comparing a character to an integer. Now, char is a numeric type, so you can do this, but the results are not what you expect. The character '0' in ASCII is 48, for example.

You can convert 0 or 1 or any other single digit to its ASCII representation, by adding it to '0'.

CodePudding user response:

if (s[j] == i) => here s is defined as a character and i is defined as an integer. So to solve this problem you have to convert your integer to a character. sprintf() could work or a simple '0'.

  • Related