-2

Problem: On standard stream of input we get sequence of sets of numbers from diapason [0, 31]. Every set finished by -1. Every set may be empty and numbers may be repeated in set. You need to find XOR of all sets and output a hexadecimal representation of result, i.e we obtain {1, 2, 3}, {3, 4}, {1, 5} and result is {2, 4, 5}, thus a hexadecimal representation is 34. Each number in the result set corresponds to bit in the 32-bit hexadecimal representation.

#include <stdio.h>
#include <inttypes.h>
#include <stdint.h>

int main() {
    int32_t currentNum;
    uint32_t num = 0, result = 0;

    while (scanf("%"SCNd32, &currentNum) == 1) {
        if (currentNum != -1) {
            num |= 1 << currentNum;
        } else {
            result ^= num;
            num = 0;
        }
    }
    printf("%x\n", result);
    return 0;
}

This problem is simple and my solution is above. But I have following problem : the testing system in which I send a code return me a run-time error. I can't imagine where is mistake and I can't come up with a such test that return run-time error. Could you give me any tips?

Gassa
  • 8,546
  • 3
  • 29
  • 49
marka_17
  • 201
  • 1
  • 2
  • 7

1 Answers1

0

First, it looks like 1 << 31 is undefined behavior. See, 1 is a signed constant, and 1 << 31 is not representable in an int, so undefined. Try 1U << currentNum there to make it unsigned and well-defined.

Second, SCNd32 may not be what you expect. On my system (MinGW-w64 GCC 5.3.0 on Windows), it is not defined at all, so your program just does not compile. Thus I can imagine it can be defined to mean something other as well, and then compile but fail at runtime. Try a simple "%d" or "%i" there.

Third, some online judges may be configured so that calling certain functions is restricted by terminating after a call to them at runtime. One of such functions may be scanf if, for example, the judge admins think you should use fgets for some weird reason, or iostream if the language is in fact C++. This however is already guess territory. Try reading the judge documentation to see if this is the case.

Community
  • 1
  • 1
Gassa
  • 8,546
  • 3
  • 29
  • 49
  • 1
    This surprises me, that the `SCNd32` macro is not defined at all in MinGW. Note that the Standard requires that this macro be defined in `inttypes.h` if the system supports 32 bit fixed-width integers. – ad absurdum Jan 07 '17 at 04:50
  • 1
    Yes, problem was in 1 << 31. – marka_17 Jan 07 '17 at 13:05