ProgrammingVery hardProduct company OA · code-tracing level
What will be the output of the following pseudocode? (Integers are in two's complement, so −i flips the bits of i and adds 1; & is bitwise AND.)
What will be the output of the following pseudocode? (Integers are in two's complement, so −i flips the bits of i and adds 1; & is bitwise AND.)
Integer s = 0
for (each i from 1 to 32)
s = s + (i & (-i))
end for
Print s- A. 96
- B. 528
- C. 80
- D. 112
Correct answer: D. 112
i & (−i) keeps only the lowest set bit of i. Among 1…32, 16 numbers have lowest bit 1, 8 have 2, 4 have 4, 2 have 8, 1 has 16 (namely 16) and 1 has 32. Each group from 1 to 16 contributes 16, so the sum is 5 × 16 + 32 = 112. 528 = 1 + … + 32 treats i & (−i) as i; 96 forgets the 32.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (& is bitwise AND.) Integer c = 0, x for (each i from 0 to 63) x = i while (x > 0) x…
- What will be the output of the following pseudocode? Integer n = 30, c = 0, j for (each i from 1 to n) j = i while (j <= n) c = c + 1 j =…
- What will be the output of the following pseudocode? Integer c = 0 for (i = 1; i <= 100; i = i 2) for (j = i; j <= 100; j = j + 1) c = c +…
- What will be the output of the following pseudocode? // 32-bit signed integers; overflow wraps around (two's complement); / truncates…
- What is the time complexity of the following pseudocode, as a function of n? for (i = n; i > 0; i = i / 2) for (j = 0; j < i; j = j + 1)…
- What is the time complexity of the following pseudocode, as a function of n? for (i = 1; i <= n; i = i + 1) j = 1 while (j < i) j = j 2…