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
Follow up: Could you solve it without loops/recursion?
通过次数27,166提交次数55,541
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/power-of-four
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
首先判断是不是2的次方,判断 n & (n - 1) ==0。再判断是不是4的次方,如果是的话,那么,1会出现在奇数位,那么直接&0101010101010101即可。
class Solution {
public boolean isPowerOfFour(int num) {
int ans = num & (num - 1);
if (ans != 0) {
return false;
}
return (num & 0x55555555) !=0;
}
}
本文介绍了一个高效的方法来判断一个32位有符号整数是否为4的幂。通过位运算判断该数是否为2的幂,并进一步确认其是否满足4的幂的条件。文章提供了一个简洁的Java代码示例。
746

被折叠的 条评论
为什么被折叠?



