Bird
Raised Fist0

Which modification to the bit manipulation approach is correct?

hard🎤 Interviewer Follow-up Q15 of Q15
Bit Manipulation - Power of Two
Suppose you want to check if a number is a power of two but the input can be negative or zero, and you want to handle 64-bit integers efficiently. Which modification to the bit manipulation approach is correct?
AUse the condition n > 0 and (n & (n - 1)) == 0 to handle all cases correctly.
BUse n & (n + 1) == 0 to handle negative numbers as well.
CUse floating point division to check if log2(n) is an integer for negative inputs.
DIgnore negative inputs and only check positive numbers with n & (n - 1) == 0.
Step-by-Step Solution
Solution:
  1. Step 1: Understand input constraints

    Negative and zero inputs are not powers of two, so must be excluded explicitly.
  2. Step 2: Apply correct bit manipulation check

    Check n > 0 first, then use n & (n - 1) == 0 to verify exactly one set bit.
  3. Step 3: Confirm correctness for 64-bit integers

    This approach works efficiently for 64-bit integers as well, since bitwise ops are constant time.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Explicit positive check avoids errors on zero/negative inputs [OK]
Quick Trick: Always check n > 0 before bitwise power-of-two test [OK]
Common Mistakes:
MISTAKES
  • Using incorrect bitwise operations
  • Ignoring negative inputs
  • Using floating point logs causing precision errors
Trap Explanation:
PITFALL
  • Some think bitwise trick works for all integers without input validation, which is false.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to adapt solutions to input constraints and data types.
Master "Power of Two" 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