您的位置:首页 > 其它

326. Power of Three LeetCode解题报告

2016-01-13 17:48 405 查看
Given an integer, write a function to determine if it is a power of three.

Follow up:

Could you do it without using any loop / recursion?

解法一:采用循环,O(lg(N))的速度

class Solution {
public:
bool isPowerOfThree(int n) {

if (n == 1 || n == 3 )
return true;
if (n<3)
return false;

int i = 2;
while(true)
{
if(pow(3,i) ==n)
return true;
else if (pow(3,i) > n)
return false;
else
++i;
}

}
};


解法二:采用递归方法

class Solution {

public:
bool isPow3(int n, int step){
if(pow(3,step) == n)
return true;
else if(pow(3,step) > n)
return false;
else
return  isPow3(n,++step);
}

bool isPowerOfThree(int n) {
int step = 0;
return isPow3(n,step);

}
};


解法三

return n>0 ? !(1162261467%n):0;


解法四

return (n == 1 || n == 3 || n == 9 || n == 27 || n == 81 || n == 243 || n == 729 || n == 2187 || n == 6561 || n == 19683 || n == 59049 || n == 177147 || n == 531441 || n == 1594323 || n == 4782969 || n == 14348907 || n == 43046721 || n == 129140163 || n == 387420489 || n == 1162261467);


解法5

bool isPowerOfThree(int n) { double logRes = log10(n)/log10(3); return (logRes - int(logRes) == 0) ? true : false; }


The code implements the base change rule of the logarithm. it basically looks at if base3 logarithm of the number is an integer or not.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode power