CodeSignal Technical Assessment Bit Manipulation and Mathematical Reasoning 1 — Questions and Answers
Question 1: What does the expression `n & (n-1)` evaluate to when n is a power of 2?
- n
- 0 (Correct answer)
- 1
- n-1
Correct answer: 0
A power of 2 has exactly one set bit; subtracting 1 flips all lower bits, so ANDing gives 0.
Question 2: How do you check if the k-th bit (0-indexed) of integer n is set?
- n | (1 << k)
- n & (1 << k) (Correct answer)
- n ^ (1 << k)
- n >> k & 0
Correct answer: n & (1 << k)
Shifting 1 left by k positions creates a mask; ANDing with n isolates that bit, giving a non-zero result if it is set.
Question 3: What is 5 XOR 3 in decimal?
- 2
- 6 (Correct answer)
- 7
- 8
Correct answer: 6
5 is 101 and 3 is 011 in binary; XOR gives 110, which equals 6 in decimal.
Question 4: What does left-shifting an integer n by 1 position (`n << 1`) effectively compute?
- n / 2
- n * 2 (Correct answer)
- n + 1
- n - 1
Correct answer: n * 2
Left-shifting by 1 appends a zero bit on the right, which doubles the value in base-2 representation.
Question 5: Which bit trick isolates the lowest set bit of integer n?
- n & (n+1)
- n & (-n) (Correct answer)
- n | (n-1)
- n ^ (n-1)
Correct answer: n & (-n)
The two's complement of n (-n) flips all bits and adds 1, so n & (-n) keeps only the rightmost set bit.
Question 6: What is the result of `n ^ n` for any integer n?
- n
- 0 (Correct answer)
- 1
- 2n
Correct answer: 0
XORing any value with itself cancels every bit, producing 0.
What does the expression `n & (n-1)` evaluate to when n is a power of 2?