Bird
Raised Fist0

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

medium🐞 Bug Identification Q7 of Q15
Bit Manipulation - Power of Two
Identify the issue in the following Python 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
AThe function should return <code>n == 0</code> instead of <code>n == 1</code>
BThe loop condition should be <code>n > 1</code> instead of <code>n % 2 == 0</code>
CThe function does not handle negative numbers correctly
DUsing floating-point division instead of integer division causes incorrect results
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the division operation

    The code uses n /= 2, which performs floating-point division in Python 3.
  2. Step 2: Effect on loop and comparison

    This converts n to a float, so the loop condition and final comparison n == 1 may fail due to floating-point precision.
  3. Step 3: Correct approach

    Use integer division n //= 2 to keep n an integer and ensure correct logic.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Use integer division for exact results [OK]
Quick Trick: Use integer division (//) to avoid float errors [OK]
Common Mistakes:
MISTAKES
  • Using / instead of // for division
  • Ignoring float precision issues
  • Assuming loop condition is incorrect
Trap Explanation:
PITFALL
  • Floating-point division looks like division but changes data type
Interviewer Note:
CONTEXT
  • Tests attention to detail and understanding of Python division
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