Bird
Raised Fist0

If the input number n can be negative or zero, and you want to check if its absolute value is a power of four, which modification to the optimal logarithm-based approach is correct?

hard🎤 Interviewer Follow-up Q15 of Q15
Bit Manipulation - Power of Four
If the input number n can be negative or zero, and you want to check if its absolute value is a power of four, which modification to the optimal logarithm-based approach is correct?
ARemove the check for n <= 0 and directly compute log2(n)/2
BAdd a check to return False if n is zero or negative before applying logarithm on abs(n)
CUse the brute force iterative division approach instead, as logarithm fails for negative inputs
DTake the absolute value of n before the logarithm check and keep the rest unchanged
Step-by-Step Solution
Solution:
  1. Step 1: Consider input domain

    Since n can be zero or negative, these are not powers of four, so must return False immediately.
  2. Step 2: Apply logarithm check on absolute value

    After filtering invalid inputs, apply logarithm on abs(n) to check power of four.
  3. Step 3: Finalize correct approach

    Adding a check to return False for zero or negative inputs before log check ensures correctness and avoids math domain errors.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Zero and negatives are filtered out before log check on abs(n) [OK]
Quick Trick: Filter invalid inputs before log check on abs(n)
Common Mistakes:
MISTAKES
  • Removing input validation
  • Applying log on negative numbers causing errors
Trap Explanation:
PITFALL
  • Taking abs without filtering zero or negatives causes math domain errors or incorrect results.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to adapt solution to relaxed constraints and handle edge cases robustly.
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