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
Example 1:
Input: n = 27
Output: true
Example 2:
Input: n = 0
Output: false
Example 3:
Input: n = 9
Output: true
Example 4:
Input: n = 45
Output: false
Constraints:
$-2^{31} \leq n \leq 2^{31} - 1$
By continually dividing n
by three if the remainder is not equal to n
. If the result equals
- Sunday, 14 March, 2021
- Time Complexity:
$O(\log_{3}{n})$ - Space Complexity:
$O(1)$ - Runtime: 12 ms, faster than 75.21% of C online submissions for Power of Three.
- Memory Usage: 6.4 MB, less than 45.35% of C online submissions for Power of Three.
bool isPowerOfThree(int n) {
if (n < 1) return false;
while (n % 3 == 0) {
n /= 3;
}
return n == 1 ? true : false;
}