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?
解题思路
如果一个数为4n,则它等于n个4相乘。乘以4可以化为左移2位的位运算,因此4n规律如下:
0000000000000001
0000000000000100
0000000000010000
0000000001000000
0000000100000000
二进制表示中仅有一个1,且1位于奇数位处。
可将此题与 Power of Two进行类比,主要区别在于判断等于1的位是否位于奇数位处。
实现代码
// Runtime: 2 ms
public class Solution {
public boolean isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0 ;
}
}