Found a summary of some solutions of this problem, thought that these are interesting and it is worth to record all these ideas.
Recursive Solution
|
|
Iterative Solution
|
|
Other Method 1
|
|
Or simply hard code it since we know maxPowerOfThree = 1162261467
:
|
|
It is worthwhile to mention that Method 1 works only when the base is prime. For example, we cannot use this algorithm to check if a number is a power of 4 or 6 or any other composite number.
Other Method 2
If log10(n) / log10(3)
returns an int (more precisely, a double but has 0 after decimal point), then n is a power of 3. But be careful here, you cannot use log
(natural log) here, because it will generate round off error for n=243
. This is more like a coincidence. I mean when n=243
, we have the following result:
|
|
This happens because log(3)
is actually slightly larger than its true value due to round off, which makes the ratio smaller.
|
|
Other Method 3
|
|
Other Method 4
|
|
Cheating Method
Array:
|
|
HaseSet:
|
|
Radix-3 Method
The idea is to convert the original number into radix-3 format and check if it is of format 10*
where 0*
means k
zeros with k>=0
.
|
|