Bird
Raised Fist0

Consider the following Python function to check if n is a power of four:

medium🐞 Bug Identification Q7 of Q15
Bit Manipulation - Power of Four
Consider the following Python function to check if n is a power of four:
def checkPowerOfFour(n):
    return n > 0 and (n & (n - 1)) == 0 and (n & 0x55555555) != 0

What is the subtle bug in this code?
AThe mask 0x55555555 is incorrect for 64-bit integers
BThe condition (n & (n - 1)) == 0 incorrectly allows zero
CThe function does not handle negative inputs correctly
DThe bitwise AND with 0x55555555 should be equality to zero
Step-by-Step Solution
Solution:
  1. Step 1: Understand the mask usage

    The mask 0x55555555 selects bits in odd positions for 32-bit integers.
  2. Step 2: Consider integer size

    On 64-bit systems, this mask only covers lower 32 bits, missing higher bits.
  3. Step 3: Identify the bug

    For 64-bit integers, the mask should be 0x5555555555555555 to cover all bits.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Mask length must match integer size [OK]
Quick Trick: Mask must cover all bits for correct power-of-four check [OK]
Common Mistakes:
MISTAKES
  • Assuming 32-bit mask works on 64-bit integers
  • Confusing zero check with power-of-two check
  • Ignoring negative input handling
Trap Explanation:
PITFALL
  • Option B is wrong because zero is excluded by n > 0; Option D reverses mask logic.
Interviewer Note:
CONTEXT
  • Tests knowledge of bitmasking and system architecture differences.
Master "Power of Four" in Bit Manipulation

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bit Manipulation Quizzes