Skip to content

Latest commit

 

History

History
61 lines (43 loc) · 1.19 KB

326. Power of Three.md

File metadata and controls

61 lines (43 loc) · 1.19 KB

1. Description

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 = 3^x$.

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$

2. Solutions

Solution 1: Language: C Loop Iteration

By continually dividing n by three if the remainder is not equal to $0$, we would found the less factor of the integer n. If the result equals $1$, the number must be a multiple of 3; otherwise, it is not.

  • 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;
}