A. The expression should be (n | (n - 1)) == 0 instead.
B. It does not check if n is positive, so zero or negative numbers return true incorrectly.
C. The function should return an integer, not a boolean.
D. The bitwise AND operator is used incorrectly; it should be OR.
Solution
Step 1: Analyze the bitwise condition
The expression (n & (n - 1)) == 0 is true for powers of two but also for zero.
Step 2: Identify missing condition
Zero and negative numbers are not powers of two, so the function must check n > 0.
Final Answer:
It does not check if n is positive, so zero or negative numbers return true incorrectly. -> Option B
Quick Check:
Check n > 0 to avoid false positives [OK]
Hint: Always check n > 0 when using bitwise power of two check [OK]
Common Mistakes:
Omitting n > 0 check
Using wrong bitwise operator
Returning wrong data type
5. You want to write a function that returns the smallest power of two greater than or equal to a given positive integer n. Which approach correctly achieves this in C#?
hard
A. Use a loop doubling a variable starting at 1 until it is >= n.
B. Return n & (n - 1) to get the smallest power of two.
C. Return n | (n - 1) to get the smallest power of two.
D. Return n ^ (n - 1) to get the smallest power of two.
Solution
Step 1: Understand the problem requirement
We need the smallest power of two >= n, so start from 1 and double until reaching or exceeding n.
Step 2: Analyze other options
Bitwise operations like AND, OR, XOR with n-1 do not produce the smallest power of two >= n.
Final Answer:
Use a loop doubling a variable starting at 1 until it is >= n. -> Option A
Quick Check:
Doubling loop finds smallest power of two >= n [OK]
Hint: Double from 1 until >= n to find smallest power of two [OK]
Common Mistakes:
Using bitwise AND/OR/XOR incorrectly for this task
Not handling n less than 1
Assuming bitwise ops give next power of two
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.