Problem Statement: Given an integer n, return true if it is a power of 2. Otherwise, return false.
Example 1: Input: n = 2 Output: true Explanation: 2^1 = 2 Example 2: Input: n = 16 Output: true Explanation: 2^4 = 16 Example 3: Input: n = 3 Output: false
Understanding the Recursive Idea.
Breaking Down the Recursive Approach.
C# Recursive Code Implementation.
public class Solution { public bool IsPowerOfTwo(int n) { //Step 1: Handle Negative Numbers and Zero if(n <= 0) return false; //Step 2: Base Case if(n == 1) return true; //Step 3: Check Divisibility if(n % 2 != 0) return false; //Step 4: Recursive Call return IsPowerOfTwo(n / 2); } }
Dry Run Example: n = 16
- 16 > 0
- 16 != 1
- 16 % 2 == 0
- 8 > 0
- 8 != 1
- 8 % 2 == 0
- 4 > 0
- 4 != 1
- 4 % 2 == 0
- 2 > 0
- 2 != 1
- 2 % 2 == 0
- Now all previous calls return true.
- Final Answer will also return true.








