Given an integer, write a function to determine if it is a power of three.
Follow up:
Could do it without using any loop/recursion?
Idea 1: Use recursive functions to solve the problem, if n<=0, returns false. If n==1, returns True. If n can be divisible by 3, the function is called recursively with N/3. Otherwise, n cannot be divisible by 3, and naturally it cannot be a power of 3, returning false.
classSolution { Public: BOOLIspowerofthree (intN) {if(n<=0) return false; if(n==1) return true; if(n%3==0) returnIspowerofthree (n/3); return false; }};
Idea 2: Using the log function, if LOG3 (n) is an integer, then the power of N is 3. However, the use of the log function will result in rounding problems, which are caused by precision. We can take special measures to determine whether n is equal to 3 Log3 (n), in order to circumvent round off error, we take POW (3,round (LOG3 (n))), round function to calculate the LOG3 (n) is rounded.
class Solution {public: bool ispowerofthree (int n) { If(n<1) returnfalse; return N==pow (3, round (log (n)/log (3)));} ;
326. Power of three