326.3的幂
题目链接
比较好想的是取对数法。
class Solution {
public:
double eps = 1e-11;
bool isPowerOfThree(int n) {
if(n<=0)return 0;
double pw = log2(n) / log2(3.0);
return fabs(round(pw) - pw) < eps ? 1 : 0;
}
};
另外可以找到int范围内最大的幂,取模
static const auto io_speed_up = []()
{
ios::sync_with_stdio(false);
cin.tie(0);
return 0;
}();
class Solution {
public:
bool isPowerOfThree(int n) {
return n>0&&1162261467%n==0;
}
};
342.4的幂
题目链接
比较显然的思路是判断是不是2的幂然后判断是不是4的幂
假设已经知道是2的幂,那么可以通过看2进制从低到高的奇数位是不是1来判断。
static const auto io_speed_up = []()
{
ios::sync_with_stdio(false);
cin.tie(0);
return 0;
}();
class Solution {
public:
bitset<32>odn = bitset<32>(0xaaaaaaaa);
bool isPowerOfFour(int num) {
bitset<32>n(num);
return n.count()==1&&(n&odn).count()==0;
}
};
或者可以通过n%3==1来判断是不是4的幂。