↓Skip to main content
  1. LeetCode/

LeetCode 326: Power of Three

·1 min· ·
LeetCode Easy Math Recursion
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted (first try)

Approach
#

n <= 0 never qualifies. With a loop: divide by 3 while n % 3 == 0 and check that 1 remains. Without loops: the largest power of three in 32 bits is 3^19 = 1162261467, and since 3 is prime its divisors are exactly the powers of three: n > 0 and 3**19 % n == 0 (Number Theory).

My Solution
#

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

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • Exclude 0 and negatives.
  • The trick works only for powers of a prime: with a composite base such as 4, divisors of the top power need not be powers of it; 2 divides 4^15 but is not a power of 4.

Interview Explanation
#

Since 3 is prime, every divisor of 3^19, the largest power of three in 32 bits, is a power of three, so I check that n is positive and divides 3^19. Time O(1).

Related

LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive
LeetCode 263: Ugly Number
·1 min
LeetCode Easy Math
LeetCode 263 note: only positive numbers can be ugly; divide out every factor 2, 3 and 5 and check whether 1 remains
LeetCode 292: Nim Game
·1 min
LeetCode Easy Math Brainteaser Minimax-Algorithm Game-Theory
LeetCode 292 note: whoever faces a multiple of 4 stones loses, so the first player wins when n % 4 != 0
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 367: Valid Perfect Square
·1 min
LeetCode Easy Math Binary-Search
LeetCode 367 note: binary search [1, num] for mid² == num without using sqrt