ccounting

Hidden test cases failed in a c program to count number of digits


I'm trying to solve a question in our C programming lab. This is a program about finding number of digits in a number.

I somehow managed to code the solution but the issue is that the hidden test cases always fail no matter what I do.

The main visible test cases pass the test without any errors but the hidden test cases always fail and I can't view them.

This is my code

#include <stdio.h>

int main() {
    int n;
    int count = 0;
    scanf("%d", &n);
    if (n < 1) {
        n = -n;
    }
    while (n > 0) {
        n /= 10;
        count++;
    }
    printf("Number of digits: %d\n", count);
}

and these are the test cases and their outputs Test case 1:

Input: 12345
Output: Number of digits: 5

Test case 2:

Input: 987654321
Output: Number·of·digits:·9

These test cases run successfully without any errors but the hidden test cases, 4 of them, don't work.


Solution

  • If you can assume that the program input always consists of an integer in the range of type int, you still fail for 2 cases:

    You can count the number of digits in both positive and negative numbers this way:

    #include <stdio.h>
    
    int main() {
        int n, count;
    
        if (scanf("%d", &n) != 1) {
            printf("not a number\n");
            return 1;
        }
        count = 0;
        for (;;) {
            count++;
            n /= 10;
            if (n == 0)
                break;
        }
        printf("Number of digits: %d\n", count);
        return 0;
    }
    

    If the user is allowed to type numbers in octal or hexadecimal format, you should use scanf("%i", &n) to recognise these alternative syntaxes.