Bird
Raised Fist0

Suppose you want to check if a number is a power of two but the input can be a floating-point number. Which approach would you use?

hard🎤 Interviewer Follow-up Q10 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 a floating-point number. Which approach would you use?
AUse a tolerance-based check on logarithm base 2 to handle floating-point precision
BUse repeated division by 2 until 1 or non-divisible
CUse logarithm base 2 and check if result is integer
DUse n & (n - 1) bitwise trick after casting to int
Step-by-Step Solution
Solution:
  1. Step 1: Understand floating-point input

    Bitwise operations require integers; casting floats may lose precision or be invalid.
  2. Step 2: Use logarithm base 2 with tolerance

    Checking if log2(n) is close to an integer within a small epsilon accounts for floating-point precision issues.
  3. Step 3: Avoid direct equality checks

    Direct equality checks on floating-point results are unreliable; tolerance-based checks are standard.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Tolerance-based log2 check is standard for floating-point power of two checks [OK]
Quick Trick: Use log2 with tolerance to check integer result for floats [OK]
Common Mistakes:
MISTAKES
  • Casting float to int blindly
  • Using bitwise ops on floats
  • Checking exact equality on log2
Trap Explanation:
PITFALL
  • Candidates often try bitwise ops on floats or rely on exact equality checks with log2.
Interviewer Note:
CONTEXT
  • Tests ability to adapt power of two checks to floating-point inputs.
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