leetcode - 326. Power of Three

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 == 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:

-2^31 <= n <= 2^31 - 1

Follow up: Could you solve it without loops/recursion?

Solution

Binary Search

Search all the possible numbers for the power of 3.

Time complexity: o ( log ⁡ n ) o(\log n) o(logn)
Space complexity: o ( 1 ) o(1) o(1)

Note: Use 20 as the initial value for right, because 3^20 is larger than integer.

Prime factorization

This can be used to any other prime numbers as well. Since 3 is prime. 3^19 is its own unique prime factorization. Hence it is only divisible by its 20 factors, all of which are in the form of 3^n, where n = 0,1,…19.
On the other hand, 4^19 is not its own unique prime factorization. 4^19 = 2^38. (19 in this example is arbitrary)

Ref: https://leetcode.com/problems/power-of-three/solutions/77856/1-line-java-solution-without-loop-recursion/comments/1186997

Time complexity: o ( 1 ) o(1) o(1)
Space complexity: o ( 1 ) o(1) o(1)

Code

Binary Search

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n <= 0:
            return False
        left, right = 0, 19
        while left < right:
            mid = (left + right) >> 1
            if math.pow(3, mid) < n:
                left = mid + 1
            else:
                right = mid
        return math.pow(3, (left + right) >> 1) == n

Prime Factorization

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        # 1162261467 is 3 ^ 19
        return n > 0 and 1162261467 % n == 0

你可能感兴趣的:(OJ题目记录,leetcode,算法,java)