您的位置:首页 > 其它

[leetcode] 326. Power of Three

2016-06-02 10:43 369 查看
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?

check n =? 3^x

Solution 1

Idea: divide 3 to see whether get 0 residue

class Solution {
public:
bool isPowerOfThree(int n) {
while (n!=0 && n%3==0){
n= n/3;
}
return n==1;
}
};

Solution 2

Idea: if n=3^x, then log10(n) = xlog10(3), log10(n)/log10(3) is integer

class Solution {
public:
bool isPowerOfThree(int n) {
if (n < 0)
return false;
else{
return (int(log10(n)/log10(3))-(log10(n)/log10(3)) ==0);
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode easy