Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example: Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Credits:
这道题让我们判断一个数是否为4的次方数,那么最直接的方法就是不停的除以4,看最终结果是否为1,参见代码如下:
解法一:
class Solution {
public:
bool isPowerOfFour(
int num) {
while (num && (num %
4 ==
0)) {
num /=
4;
}
return num ==
1;
}
};
还有一种方法是跟Power of Three中的解法三一样,使用换底公式来做,讲解请参见之前那篇博客:
解法二:
转载请注明原文地址: https://ju.6miu.com/read-1294899.html