problem:
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
tip:
判断一个数是否是4的幂级数。
solutions:
1.最直接,首先想到的方法:
class Solution {
public:
bool isPowerOfFour(int num) {
int n = num;
while(n && (n%4==0))
n = n/4;
return n==1;
}
};
2.使用换底公式,只能使用以10为底(具体原因参见参考博客)。
class Solution {
public:
bool isPowerOfFour(int num) {
int n = num;
return n && (int)(log10(n)/log10(4))-(log10(n)/log10(4))==0;
}
};
3.参照2的幂级数:
最高位为1,减1后与自身做&运算结果为0,同时是4的幂级数的数减1后刚好是3的整数倍。
class Solution {
public:
bool isPowerOfFour(int num) {
int n = num;
return (n>0)&&(!(n&(n-1)))&&(!((n-1)%3));
}
};