how many times does i occur in x (unsigned 32 bit int C)

83 views Asked by At

This is a little bit confusing for me, but I have to see how many times i occurs in x. So if someone types 3 for i and x is 4294967295, it should then say 0 times, but if someone types in 9 for i and 4294967295 for x, it should say 3 times.

This is what I have, but output says 0 with 9, so it's not working ..

int main(int argc, char** argv) {
    unsigned int i;
    scanf("%u", &i);
    unsigned int x;
    scanf("%u", &x);
    int output = 0;
    int t = 0;
    while (t < 10) {
        x /= 10;
        if (i == x) {
            output++;
        }
        t++;
    }
    printf("%d", output);
}
3

There are 3 answers

5
Antoine On BEST ANSWER
int main(int argc, char** argv) {

    unsigned int i;
    scanf("%u", &i);
    if(i > 9) {                                 // check it's a single digit
        printf("expecting a single digit\n");
        return 1;                               // to indicate failure
    }

    unsigned int x;
    scanf("%u", &x);

    int output = 0;      // initialized output, removed t (use x directly instead)
    if(x == 0) {         // special case if x is 0
        if(i == 0) {
            output = 1;
        }
    } else {

        while(x > 0) {         // while there is at least a digit
            if(i == (x % 10)) {  // compare to last digit
                output++;
            }
            x /= 10;            // remove the last digit
        }

    }

    printf("%d\n", output);    // added \n to be sure it's displayed correctly
    return 0;                  // to indicate success

}

Also I recommend using more explicit variable names, like digit and number instead of x and i.

1
Some programmer dude On

The problem is that you compare i with the whole of x, instead of checking each digit of x.

The easiest solution is probably to read i as a character, make sure it's a digit. Then read x as a string (and make sure it's all digits as well). Then for each character in the string x compare it against i.

0
ajay On

You should extract each digit from x and compare it against the digit i.

#include <stdio.h>

int main(void) {
    unsigned int i;
    scanf("%u", &i);
    unsigned int x;
    scanf("%u", &x);
    int output = 0;
    int t = 0;
    while(x > 0) {   
        t = x % 10;  // least significant digit of x
        if(t == x) {
            output++;
        }
        x /= 10;  
    }
    printf("%d", output);
}