[LeetCode 231] Power of Two
LeetCode 231 (Java)
[Power of Two] 문제 풀이
[LeetCode 231] Power of Two
Description
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: 2^0 = 1
Example 2
- Input: n = 16
- Output: true
- Explanation: 2^4 = 16
Example 3
- Input: n = 3
- Output: false
Constraints
-2^31 <= n <= 2^31 - 1
Code
내 제출
1
2
3
4
5
6
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}
| Runtime | Memory |
|---|---|
| 0 ms | 41.3 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public boolean isPowerOfTwo(int n) {
if(n<=0){
return false;
}
if(n==1){
return true;
}
if(n%2!=0){
return false;
}
else{
return isPowerOfTwo(n/2);
}
}
}
Reference
- https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0231.Power%20of%20Two/Solution.java
This post is licensed under CC BY 4.0 by the author.
