您的位置:首页 > 其它

Leetcode——326. Power of Three

2017-01-21 20:27 471 查看

题目

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?

解答

Method1:循环或者递归

public boolean isPowerOfThree(int n) {
return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3)));
}


public boolean isPowerOfThree(int n) {
if(n>1)
while(n%3==0) n /= 3;
return n==1;
}


因为3是质数,所以可以用最大的3的幂次和n求模来计算。

最大的的3的幂次:

int MaxPowerOfThree=(int) pow(3,(int)(log10(INT_MAX)/log10(3)));


AC code

class Solution {
public:
bool isPowerOfThree(int n) {
int MaxPowerOfThree=(int) pow(3,(int)(log10(INT_MAX)/log10(3)));
return n>0&&MaxPowerOfThree%n==0;
}
};


Or simply hard code it since we know maxPowerOfThree = 1162261467:

public boolean isPowerOfThree(int n) {
return n > 0 && (1162261467 % n == 0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: