Given an integer, write a function to determine if it is a power of three.
方法一:
class Solution {
public:
bool isPowerOfThree(int n) {
if(n == 1){
return 1;
}
while(n >= 3){
if((n % 3) != 0){
return 0;
}
n = n / 3;
}
if(n == 1){
return 1;
}
else{
return 0;
}
}
};
方法二:如果n可以实现经过 log10(n)/log10(3)运算得到整数,则n是power of Three;
其中fomd是用来计算含有小数部分的取余运算;
(%百分号只能计算整数的取余运算)
class Solution {
public:
bool isPowerOfThree(int n) {
return fmod(log10(n)/log10(3), 1)==0;
}
};