问题描述
Given an integer, write a function to determine if it is a power of x.
在这里,我们考虑x=2,3,4三种情况
Follow up:
Could you do it without using any loop / recursion?
一般解法
以x==3为例
bool isPowerOfThree(int n) {
while (n >= 1)
{
if (n == 1 || n == 3)
return true;
else
{
if (n % 3) break;
n /= 3;
}
}
return false;
}
特殊解法
x==2
bool isPowerOfTwo(int n) {
return n>0 && (n&(n-1))==0;
}
x==4
基于x为2,考虑4的整数次幂的二进制中1都在特殊的位置,因此我们使用”num & 0x55555555==num”来检验是否位置正确。
bool isPowerOfFour(int num) {
return num>0 && (num&(num-1))==0 && (0x55555555&num)==num;
}
x==3
在这里借助log换底公式求其对应整数次,然后由于直接(log(n)/log(3))在测试243时会报错,所以添加了round()。
bool isPowerOfThree(int n) {
return n>0 && (n==pow(3,round(log(n)/log(3))));
}