본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 326. Power of Three

반응형

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

 

Power of Three - LeetCode

Power of Three - Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x.   Example 1: Input: n = 27 Output: true Explanation: 27 = 33 Example 2:

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 풀이과정

i가 n보다 작은 동안 3씩 곱해주며 n과 같은지를 비교합니다. int범위를 초과할 수 있으므로 i는 long long으로 선언해줍니다.

📔 정답 출력 | 반환

n과 같다면 true 아니면 false를 반환해줍니다.


📕 Code

📔 C++

class Solution {
public:
    bool isPowerOfThree(int n) {
        for(long long i = 1; i <= n; i *= 3) {
            if(i == n) return true;
        }
        return false;
    }
};

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