File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 231. Power of Two
3+ * Difficulty: Easy
4+ * URL: https://leetcode.com/problems/power-of-two/description/
5+ *
6+ * ---------------------
7+ * Approach 1: Iterative Division
8+ *
9+ * - A number `n` is a power of two if it can be written as 2^k (where k ≥ 0).
10+ * - If `n` is positive and divisible by 2, we keep dividing it by 2.
11+ * - If after dividing repeatedly, the result becomes 1, then it was a power of two.
12+ * - Otherwise, it is not.
13+ *
14+ * Example:
15+ * n = 16 → 16/2=8 → 8/2=4 → 4/2=2 → 2/2=1 ✅ Power of Two
16+ * n = 12 → 12/2=6 → 6/2=3 ❌ not 1 → Not a Power of Two
17+ *
18+ * ---------------------
19+ * Time Complexity: O(log n)
20+ * - In each step we divide by 2 → about log₂(n) steps.
21+ *
22+ * Space Complexity: O(1)
23+ * - Only using a few variables, no extra space.
24+ */
25+ class Solution {
26+ public boolean isPowerOfTwo (int n ) {
27+ if (n <= 0 )
28+ return false ;
29+ while (n % 2 == 0 ) {
30+ n = n / 2 ;
31+ }
32+ return n == 1 ;
33+ }
34+ }
You can’t perform that action at this time.
0 commit comments