Power of Three

The largest int32 power of 3 is `3^19 = 1162261467` — check whether n divides it.

Easy
Time O(1) Space O(1)
LeetCode
2 min read
math

Problem#

Return true iff n is a positive integer power of three.

Examples#

  • n=27true; n=0false; n=9true.
  • n=45false.

Constraints#

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

Approach#

The largest 32-bit power of 3 is 3^19 = 1162261467. n is a power of 3 iff n > 0 and 1162261467 % n == 0.

Solution#

Power of Three
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
};

Editorial#

3 is prime, so every divisor of 3^19 is itself a power of 3. This collapses the test to a single modulo. The alternative while (n % 3 == 0) n /= 3; return n == 1; is also O(log n) and just as clear if you don’t recall the constant.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.