Skip to content

Commit 6271de6

Browse files
authored
Time complexity: O(log n) Space complexity: O(1)
Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false
1 parent b35e74d commit 6271de6

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

0231. Power of Two

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
public boolean isPowerOfTwo(int n) {
3+
if (n == 0) return false;
4+
5+
while (n > 0) {
6+
if (n == 1) return true;
7+
if (n % 2 != 0) break;
8+
n /= 2;
9+
}
10+
return false;
11+
}
12+
}
13+
14+

0 commit comments

Comments
 (0)