[LeetCode] 326. Power of Three with java
Problem
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
Example 2:
Input: n = 0
Output: false
Example 3:
Input: n = 9
Output: true
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
Solution
Logic
-
int형 정수의 범위 내에서 3의 제곱 중 가장 큰 수를 구한다.
-
정수 n이 3의 제곱에 해당하는 수가 되려면 1번에서 구한 숫자를 나눴을 때 나머지가 0이 되어야하고, 0보다 큰 값을 가져야 한다.
Code
class Solution { public boolean isPowerOfThree(int n) { int max = 1_162_261_467; /* max power of three */ return 0 < n && max % n == 0; } }
Time Complexity
- 정수 n의 크기를 n이라 가정할 때, n의 크기와 관계 없이 동일한 계산 횟수가 필요하다. 따라서 본 솔루션은 O(n)의 시간 복잡도를 가진다.
Leave a comment