Bird
Raised Fist0

Identify the bug in the following code snippet that attempts to check if a number is a power of four:

medium🐞 Bug Identification Q14 of Q15
Bit Manipulation - Power of Four
Identify the bug in the following code snippet that attempts to check if a number is a power of four:
AUsing 'log_val == int(log_val)' causes false negatives due to floating point precision
BThe condition 'if n <= 0' should be 'if n < 0' to allow zero
CThe division by 2 should be multiplication by 0.5 for better precision
DThe function should use a loop instead of logarithm for accuracy
Step-by-Step Solution
Solution:
  1. Step 1: Understand floating point precision issue

    Floating point calculations can introduce tiny errors, so direct equality check can fail for valid powers of four.
  2. Step 2: Identify the bug

    The line 'return log_val == int(log_val)' is the bug because it does not allow for a tolerance margin.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Adding a tolerance check like abs(log_val - int(log_val)) < epsilon fixes the bug [OK]
Quick Trick: Floating point equality without tolerance causes subtle bugs
Common Mistakes:
MISTAKES
  • Ignoring floating point errors
  • Misusing inequality conditions for input validation
Trap Explanation:
PITFALL
  • Candidates often trust direct equality on floats, missing precision issues that cause rare failures.
Interviewer Note:
CONTEXT
  • Checks candidate's awareness of floating point pitfalls in mathematical checks.
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