Search code examples
c

Test result fails for my code of Inspect Bits function


Below code is for a test sample given in https://www.testdome.com/for-developers/solve-question/9780

The question is: Implement the inspect_bits function that checks if given number contains 2 or more consecutive ones in its binary representation. If it does, the function should return 1. Otherwise, it should return 0.

For example, inspect_bits(13) should return 1 as it contains 2 consecutive ones in its binary representation (1101).

My code is:

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

int inspect_bits(unsigned int number)
{
    unsigned int ref = 1;
    int comp;

    for (int i = 0; i< sizeof(number) * 8; i++)
    {
        int a = number& (ref << i);
        printf("%d: a is %d\n", i, a);
        int b = number& (ref << (i + 1));
        printf("%d: b is %d\n", i, b);
        if ((a != 0) && (b != 0))
        {
            return 1;
        }
    }
    return 0;
}

#ifndef RunTests
int main()
{
    printf("%d", inspect_bits(13));
}
#endif  

The result seems ok, but the system tells: Various numbers: Wrong answer

Can you help to modify my code?

Regards


Solution

  • To be honest, I think it's an issue with the test site itself. Your code returns the proper results for each test case given to it, and I even modified the code as such:

    int inspect_bits(unsigned int number)
    {
        for (int i = 0; i < sizeof(number) * 8; ++i) {
            if (((number & (1 << i)) != 0) && ((number & (1 << (i + 1))) != 0)) {
                return 1;
            }
        }
        return 0;
    }
    

    The test cases return 1 where there are 2 binary values together and works for 3 and above; however, running this code on the test site and it gives the error that the Various Numbers test fails.

    Interestingly, using this code:

    int inspect_bits(unsigned int number)
    {
        while (number >= 3) {
            if ((number & 3) == 3) { return 1; }
            number >>= 1;
        }
        return 0;
    }
    

    Which does basically the same thing, only using bit-shifting on a single number, and the test passes 100% ..

    You could submit an e-mail explaining the error; but beyond that, I'm not sure what else it could be.

    Hope that helps.