Power of Three (326)
Given an integer, write a function to determine if it is a power of three.
Approach 1:
the simplest way to find if a number n
is a power of c
is simply by continually dividing n
by c
as long as the remainder is 0.
Complexity: O(log2(N) time
Approach2 :
We can solve this one just by using math. if n = 3^x
, then x = log(n) / log(3)
, and thus we come to the solution.
Here is the math:
log(n) / log(3) <==> log(3)^x / log(3) for n == 3 ^ x,
and x
is integer. Use log formula to bring x to front, we have x*log(3) / log(3)
, which is equal to x
. We only need to check if x
is an whole number by using x % 1 == 0.
Complexity: O(N) time and O(1) space.
Last updated
Was this helpful?