ProgrammingVery hardCompetitive coding (CP)
How many adjacent pairs of 1 bits does 27 (binary 11011) have? The program counts the set bits of x & (x >> 1).
How many adjacent pairs of 1 bits does 27 (binary 11011) have? The program counts the set bits of x & (x >> 1).
#include <stdio.h>
int main(void) {
unsigned x = 27, y = x & (x >> 1);
int c = 0;
while (y) { c += y & 1u; y >>= 1; }
printf("%d", c);
}- A. 3
- B. 1
- C. 2
- D. 4
Correct answer: C. 2
x & (x >> 1) has a 1 at each position where bit i and bit i + 1 of x are both set. For 11011 those are positions 0 and 3, so the count is 2.
More C Programming questions
- What is printed? c #include <stdio.h> int main(void) { int b[] = {1, 1, 0, 1, 1, 1, 0, 1, 1, 1}, run = 0, best = 0; for (int i = 0; i <…
- What is printed? c #include <stdio.h> int main(void) { int a[] = {1, 2, 3, 4, 5}; for (int i = 0; i + 1 < 5; i += 2) { int t = a[i]; a[i]…
- What is printed? c #include <stdio.h> int f(int n) { return n <= 1 ? 0 : 1 + f(n / 2); } int main(void) { printf("%d", f(10)); }
- What is printed? Assume uint16t is 16 bits. c #include <stdint.h> #include <stdio.h> int main(void) { uint16t a = 0xFFF0, b = 0x20…
- What is printed? c #include <stdio.h> long long f(int n) { return n == 0 ? 1 : 2 f(n - 1) + 1; } int main(void) { printf("%lld", f(10)); }
- What is printed? c #include <stdio.h> int main(void) { printf("%d", 1000 >> 3); }