ProgrammingHard
Which loop computes the number of trailing zeros of n in O(number of zeros) time for an unsigned n greater than zero?
- A. for (c = 0; n; c++) n = n / 10;
- B. while ((n & 1) == 0) { n >>= 1; c++; }
- C. for (c = 0; c < 32; c++) n = n + n;
- D. while (n) n = n & (n - 1);
Correct answer: B. while ((n & 1) == 0) { n >>= 1; c++; }
The loop stops at the first set bit, so its cost is the number of trailing zeros. The other loops count digits, shift for a fixed count, or count set bits.
More C Programming questions
- A loop with i starting at 1 and i = 2 until i > n runs how many times for n = 1000?
- A program uses a while loop that finds the smallest power of two at least n for n = 1000, starting from 1. What value does it return?
- int i = 0; for (; i < 5; ) i += 2; printf("%d", i); What is printed?
- int s = 0; for (int i = 1; i <= 4; i++) s += i (i % 2 ? 1 : -1); printf("%d", s); What is printed?
- int n = 0; while (++n < 10 && n % 4); printf("%d", n); What is printed?
- int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int s = 0; for (int i = 0; i < 3; i++) s += a[i][2 - i]; printf("%d", s); What is printed?