넘치게 채우기

[LeetCode] 342. Power of Four 본문

PS/LeetCode

[LeetCode] 342. Power of Four

riveroverflow 2023. 10. 23. 15:27
728x90
반응형

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

 

Power of Four - LeetCode

Can you solve this real interview question? Power of Four - Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x.   Example 1: Input: n = 16 Outp

leetcode.com

LeetCode - Power of Four

문제 유형 : 수학

문제 난이도 : Easy

 

문제

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4x.

 

정수 n이 주어진다. 4의 제곱수인지 구하시오. 

 

풀이

1. 단순한 반복문

n보다 작은동안 기준 숫자를 1부터 해서 4씩 누적해서 곱해주고, 크거나 같아졌을 때 n과 같은지 보면 된다.

2. 수학적 성질 이용하기

n이 k의 제곱수인지 확인하려면, logN/logk가 정수인지 확인하면 된다.

 

코드

C++

 

1. 반복문 풀이

class Solution {
public:
    bool isPowerOfFour(int n) {
        long long start = 1;
        while(start < n) {
            start *= 4;
        }
        return start == n;
    }
};

 

2. 로그의 성질 이용

class Solution {
public:
    bool isPowerOfFour(int n) {
        if(n==0) return false;
        return log10(n)/log10(4) == floor(log10(n)/log10(4));
    }
};
 
728x90
반응형