Bird
Raised Fist0

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

medium🐞 Bug Identification Q14 of Q15
Bit Manipulation - Power of Two
Identify the bug in the following code that attempts to check if a number is a power of two:
def isPowerOfTwo(n: int) -> bool:
    while n % 2 == 0:
        n //= 2
    return n == 1
What is the issue?
AThe return statement should check n == 0 instead of n == 1
BThe loop condition should be n > 1 instead of n % 2 == 0
CUsing integer division //= 2 causes infinite loops for odd numbers
DThe code does not handle zero or negative inputs, leading to incorrect results
Step-by-Step Solution
Solution:
  1. Step 1: Analyze input handling

    The code does not check if n is positive before the loop, so zero or negative inputs cause incorrect behavior.
  2. Step 2: Consequence of missing check

    For n=0 or negative, the loop condition n % 2 == 0 may cause infinite loop or wrong return value.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Proper input validation is required to avoid incorrect results [OK]
Quick Trick: Always check n > 0 before division loops [OK]
Common Mistakes:
MISTAKES
  • Forgetting zero/negative input checks
  • Confusing loop condition with termination condition
Trap Explanation:
PITFALL
  • Many candidates omit input validation, causing subtle bugs on edge cases.
Interviewer Note:
CONTEXT
  • Tests attention to input constraints and edge case handling.
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