250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code c++)Power of Two 본문
728x90
반응형
231. 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: true Explanation: 20 = 1
Example 2:
Input: n = 16 Output: true Explanation: 24 = 16
Example 3:
Input: n = 3 Output: false
Example 4:
Input: n = 4 Output: true
Example 5:
Input: n = 5 Output: false
Constraints:
- -231 <= n <= 231 - 1
map을 이용해 n이 2의 제곱인지 판단.
우선 for문을 통해 0부터 pow(2, i) <= INT_MAX일 때까지 반복하도록 하자.
2의 제곱에 해당하는 수가 key가 되어 true로 만들어 준다.
for문이 끝나면 바로 n을 키로 가지고, 해당 value가 true인지 확인하면 끝이다.
class Solution {
public:
bool isPowerOfTwo(int n) {
map<int, bool> m;
for(int i = 0; pow(2, i) <= INT_MAX; i++){
m[pow(2, i)] = true;
}
if(m[n]){
return true;
}
return false;
}
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)Palindrome Linked List (0) | 2021.07.27 |
---|---|
(Leet Code c++)Implement Queue using Stacks (0) | 2021.07.27 |
(Leet Code c++)Invert Binary Tree (0) | 2021.07.26 |
(Leet Code c++)Implement Stack using Queues (0) | 2021.07.26 |
(Leet Code c++)Contains Duplicate(2) (0) | 2021.07.23 |