| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
- event
- server
- array
- routes
- leetcode
- css
- Context
- nodeJS
- Props
- BinaryTree
- component
- node.js
- MySQL
- c++
- UE5
- DP
- treenode
- 비트연산
- route
- state
- Callback
- React
- Navigation
- priority_queue
- JSX
- count
- queue
- axios
- map
- bit
- Today
- Total
우사미 코딩
[Bit Manipulation] 231. Power of Two 본문
https://leetcode.com/problems/power-of-two/
Power of Two - LeetCode
Can you solve this real interview question? Power of Two - 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:
leetcode.com
주어진 입력값이 2의 거듭제곱이면 true, 아니라면 false를 반환하는 문제
1) input : n = 1
output : true (2^0 = 1)
2) input : n = 16,
output : true (2^4 = 16)
3) input : n = 3,
output : false (3은 2의 거듭제곱이 아님)
1. 반복문 (Iterative)
- Time Complexcity :: O(logN)
- Space Complexcity : (1)
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n == 0) return 0;
while(n % 2 == 0)
n /= 2;
return n == 1;
}
};
2. 재귀호출 (recursive)
- Time Complexcity : O(logN)
- Space Complexcity : O(logN) - 재귀호출 하는 만큼 스택에 쌓임
class Solution {
public:
bool isPowerOfTwo(int n) {
if(!n) return false;
if(n == 1) return true;
return n % 2 == 0 and isPowerOfTwo(n / 2);
}
};
3. Bit trick : n & (n - 1)) - Follow up: Could you solve it without loops/recursion?
- Time Complexcity : O(1)
- Space Complexcity : O(1)

입력값 n을 2진수로 바꿔보면,
2의 거듭제곱 일 때는 1비트 + 거듭제곱의 수 만큼의 0비트 로 구성되어 있는 것을 알 수 있다.
n & (n - 1) 연산을 했을 때 결과가 0이라면 그것은 n이 2의 거듭제곱이라는 뜻이다.
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && ((n & (n-1)) == 0);
}
};
'Leetcode' 카테고리의 다른 글
| [Leetcode] 153. Find Minimum in Rotated Sorted Array - 주옥같은 binary search (0) | 2023.05.17 |
|---|---|
| [LeetCode] 202. Happy Number - 주옥같은 해피넘버 (0) | 2023.05.17 |
| [Bit Manipulation] 190. Reverse Bits (0) | 2023.04.19 |
| [Bit Manipulation] 191. Number of 1 Bits - n & (n-1) trick (0) | 2023.04.18 |
| 시간복잡도, 공간복잡도 (Time complexity, Space complexity) (0) | 2023.04.18 |