Skip to content

Commit f9308d0

Browse files
authored
Create 0231-power-of-two.java
1 parent ace9281 commit f9308d0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Easy/0231-power-of-two.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

0 commit comments

Comments
 (0)