728x90
Top Interview Questions 의 Easy Collection에 있는 문제입니다.
문제는 여기서 볼 수 있습니다.
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:
Input: n = 0
Output: false
Explanation: There is no x where 3x = 0.
Example 3:
Input: n = -1
Output: false
Explanation: There is no x where 3x = (-1).
Constraints:
- -231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
Code:
class Solution:
def isPowerOfThree(self, n: int) -> bool:
# 3^x = n
MAX_NUM = 1162261467
if n > 0:
return MAX_NUM % n == 0
return False
"""
*조건 : -2^31 <= n <= 2^31 - 1
n은 자연수 3의 제곱 수여야하므로 무조건 양수이다.
MAX_NUM으로 설정한 수는 3^19으로, 2^31의 이하 범위에서 가장 큰 3의 제곱수이다.
MAX_NUM이 n으로 나눠지는 수라면 자연스럽게 n은 3의 제곱수가 된다.
0 이하의 수라면 n은 False이다.
"""
코드 설명은 주석으로 달아놓았다.
수학적으로 접근해서 보다 간편하게 풀이할 수 있었다.
정답의 수학적 특징을 캐치해서 문제풀이를 할 때 코드도 간편해지고, 시간복잡도도 낮아지는 경우가 많은 것 같다.
728x90
'알고리즘' 카테고리의 다른 글
[Leetcode/Python] House Robber (0) | 2022.11.15 |
---|---|
[Leetcode/Python] Binary Tree Level Order Traversal (0) | 2022.11.14 |
[Leetcode/Python] Shuffle an Array (0) | 2022.08.27 |
[Leetcode/Python] Symmetric Tree (2) | 2022.08.25 |
[Leetcode/Python] Maximum Subarray (0) | 2022.08.25 |