326. Power of Three LeetCode Solution

In this guide, you will get 326. Power of Three LeetCode Solution with the best time and space complexity. The solution to Power of Three problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Power of Three solution in C++
  4. Power of Three solution in Java
  5. Power of Three solution in Python
  6. Additional Resources
326. Power of Three LeetCode Solution image

Problem Statement of Power of Three

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?

Complexity Analysis

  • Time Complexity: O(1)
  • Space Complexity: O(1)

326. Power of Three LeetCode Solution in C++

class Solution {
 public:
  bool isPowerOfThree(int n) {
    return n > 0 && static_cast<int>(pow(3, 19)) % n == 0;
  }
};
/* code provided by PROGIEZ */

326. Power of Three LeetCode Solution in Java

class Solution {
  public boolean isPowerOfThree(int n) {
    return n > 0 && Math.pow(3, 19) % n == 0;
  }
}
// code provided by PROGIEZ

326. Power of Three LeetCode Solution in Python

class Solution:
  def isPowerOfThree(self, n: int) -> bool:
    return n > 0 and 3**19 % n == 0
# code by PROGIEZ

Additional Resources

See also  1899. Merge Triplets to Form Target Triplet LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.