问题描述:
Given an integer, write a function to determine if it is a power of three.
思路:给定一个整数,判断其是否是3的次幂,也就是求以3为底,n的对数是否是整数,即log3(n),若为整数,返回true,否则返回false,利用,loga(b)=log10(b)/log10(a),来进行转换,判断其是否为整数。
代码:
class Solution {
public:
bool isPowerOfThree(int n) {
return (n > 0 && int(log10(n) / log10(3)) - log10(n) / log10(3) == 0);
}
};