ProgrammingVery hardGATE CS · Campus placements
Which function correctly tests whether an unsigned value x is a power of two, with x = 0 excluded?
- A. return x & (x - 1) == 0;
- B. return (x & (x - 2)) == 0;
- C. return x && !(x & (x - 1));
- D. return x == 0 || (x & (x - 1)) == 0;
Correct answer: C. return x && !(x & (x - 1));
x & (x - 1) is zero for every power of two, but it is also zero for x = 0 after wrapping. The first form parses as x & ((x-1) == 0), which is wrong for nearly every input, and the last form accepts 0, so only the third is correct.
More C Programming questions
- char b[6]; snprintf(b, sizeof b, "%s-%d", "abcdef", 12345); int r = snprintf(NULL, 0, "%s-%d", "abcdef", 12345); printf("%s %d", b, r)…
- char b[5]; / stdin holds the nine bytes: abcdefgh and a newline / int calls = 0; do { fgets(b, sizeof b, stdin); calls++; } while…
- char s[] = "a,,b,c"; int n = 0; for (char t = strtok(s, ","); t != NULL; t = strtok(NULL, ",")) n++; printf("%d", n); What is printed?
- char d[8] = "ab"; strncat(d, "cdefgh", 3); printf("%zu", strlen(d)); What is printed?
- Which statement about the value returned by strcmp("apple", "Apple") is guaranteed by the C standard?
- char s[] = "abcdef"; memmove(s + 2, s, 4); printf("%s", s); What is printed?