ProgrammingHardGATE CS · Competitive coding (CP)
How many integers x in 1..255 have exactly four set bits? Compute with this program.
How many integers x in 1..255 have exactly four set bits? Compute with this program.
#include <stdio.h>
int main(void) {
int c = 0;
for (unsigned x = 1; x <= 255; x++) {
unsigned t = x;
int bits = 0;
while (t) { bits += t & 1u; t >>= 1; }
if (bits == 4) c++;
}
printf("%d", c);
}- A. 56
- B. 70
- C. 64
- D. 72
Correct answer: B. 70
Choosing 4 of the 8 bit positions gives C(8, 4) = 70 values, and the loop counts exactly those x in 1..255.
More C Programming questions
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 0xDEAD; int c = 0; unsigned t = x & 0xAAAA; while (t) { c += t & 1u; t…
- How many comparisons does bsearch-style binary search make to find the key 6 in the sorted array 0 to 9? Compute with the program. c…
- What is printed? c #include <stdio.h> int main(void) { int s = 0; for (unsigned i = 0; i < 8; i++) s += (i ^ (i >> 1)) & 1u; printf("%d"…
- What is printed? Assume int is 32 bits. c #include <stdio.h> int main(void) { int a = -3; unsigned b = 2; printf("%u", a b); }
- What is printed? c #include <stdio.h> int main(void) { unsigned a = 7; printf("%u", a / 2 2); }
- What is printed? c #include <stdio.h> int f(int n) { static int memo[10]; if (n < 2) return n; if (memo[n]) return memo[n]; return memo[n]…