본문 바로가기

Algorithm/Math

(C++) - LeetCode (easy) 231. Power of Two

반응형

https://leetcode.com/problems/power-of-two/description/

 

Power of Two - LeetCode

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

leetcode.com

수학 관련 함수를 사용해보는 문제였습니다.

📕 풀이방법

📔 풀이과정

1. log를 씌운다고 생각해봅니다.

2. 밑은 2 수는 n이되며 결과 값은 지수 x가 됩니다.

3. x가 정수라면 n은 2의 배수입니다.

4. 따라서 소수점에 대해 오름과 내림을 했을 때 결과값이 같다면 true를 반환해주면 됩니다.

* 0은 2의 지수로 표현될 수 없으므로 false를 반환해야 합니다.


📕 Code

📔 C++

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(!n) return false;
        return ceil(log2(n)) == floor(log2(n));
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.