Difficulty: Easy
Correct Answer: Correct
Explanation:
Introduction / Context:
This question assesses your understanding of bitwise operations in C/C++ and, specifically, the ability to test whether an integer value has more than one bit set. Knowing these idioms is essential for low-level programming, embedded work, interview questions, and performance-sensitive code such as bitmap or mask handling.
Given Data / Assumptions:
Concept / Approach:
A classic technique to determine whether an integer x has more than one bit set uses the expression x & (x - 1)
. The idea relies on the fact that subtracting 1 from a value flips the lowest set bit to 0 and turns all lower bits to 1; AND-ing with the original value removes that lowest set bit. If the result is nonzero, at least one additional set bit existed beyond the least significant one. To detect “two or more bits set,” we check if (x & (x - 1)) != 0
. To check exactly one bit set, test x != 0 && (x & (x - 1)) == 0
.
Step-by-Step Solution:
Verification / Alternative check:
Try x = 8 (binary 1000). Then x & (x - 1) = 1000 & 0111 = 0000 (exactly one bit set). For x = 10 (1010), x & (x - 1) = 1010 & 1001 = 1000 (nonzero → more than one bit set).
Why Other Options Are Wrong:
Common Pitfalls:
Forgetting to treat x == 0 as a special case; confusing the test for “exactly one bit set” with the test for “two or more bits set.”
Final Answer:
Correct.
Discussion & Comments