💡
Exercise 83

Power of Two 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Given an integer n, return True if it is a power of two: 1, 2, 4, 8, 16, 32, 64, ...

# Powers of 2: 2^0=1, 2^1=2, 2^2=4, 2^3=8, ... # Key property: keep dividing by 2, if you reach 1 → True # is_power_of_two(16) → 16/2=8 → 8/2=4 → 4/2=2 → 2/2=1 → True! # is_power_of_two(6) → 6/2=3 → 3 is odd → False!

Recursive approach:

  • Base case 1: n == 1 → return True (2^0 = 1)
  • Base case 2: n <= 0 or n is odd → return False
  • Recursive case: return is_power_of_two(n // 2)

🧠 Bit trick: A power of 2 in binary has exactly one '1' bit: n & (n-1) == 0. But let's practice the recursive approach first!

📋 Instructions
Implement `is_power_of_two(n)` recursively. Test with n = 1, 16, 6, 64, 0.
If n == 1, return True. If n <= 0 or n % 2 != 0, return False. Otherwise, recursively check n // 2.
🧪 Test Cases
Input
is_power_of_two(1)
Expected
True
Boolean check
Input
is_power_of_two(16)
Expected
True
Boolean check
Input
is_power_of_two(6)
Expected
False
Boolean check
Input
is_power_of_two(64)
Expected
True
Boolean check
Input
is_power_of_two(0)
Expected
False
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.