[Leetcode]342. Power of Four
2024. 7. 22. 15:03ㆍAlgorithm
1. 문제 :
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
Output: true
Example 2:
Input: n = 5
Output: false
Example 3:
Input: n = 1
Output: true
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
2. 풀이 :
첫 번째, while loop를 사용해서 4로 계속 나눈다. 나누다가 1이 되면 4의 거듭제곱인 거고 , 1보다 작다면 아닌 거다.
# solution 1
class Solution:
def isPowerOfFour(self, n: int) -> bool:
while n > 1:
n = n/4
if n == 1:
return True
else:
return False
두 번째, recursion을 이용한 풀이다. 4로 나눈 값을 다음함수에 넘겨버리고, 1보다 작다면 return false, 1이라면 return true를 반환한다.
# solution 2
class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n < 1:
return False
if n == 1:
return True
return self.isPowerOfFour(n / 4)
세 번째, math 모듈을 이욯하는거다. log의 성질을 이용해서 , 밑이 4인 로그 n과 int 처리한 밑이 4인 로그와의 비교를 통해 , return을 한다.
## Solution 3
import math
class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n <= 0:
return False
if n == 1:
return True
if math.log(n,4) == int(math.log(n,4)):
return True
return False
'Algorithm' 카테고리의 다른 글
[Leetcode]3211. Generate Binary Strings Without Adjacent Zeros (1) | 2024.07.24 |
---|---|
[Leetcode]53. Maximum Subarray (0) | 2024.07.23 |
[Leetcode]203. Remove Linked List Elements (0) | 2024.07.22 |
Hanoi top (2) | 2024.07.21 |
[Leetcode]234. Palindrome Linked List (0) | 2024.07.21 |