342. Power of Four【位运算】
2017/3/23 22:23:57
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?
思路:题目要求不能循环或递归,这里采用位运算与逻辑运算直接出结果。
1、指数运算是必须大于0;
2、首先满足2的指数(只有一个bit是1),利用num&num-1==0即可判断;
3、去掉只满足2的指数不满足4的指数的值,0x2AAAAAAA对应的bit位不能是1。100B = 4 属于4的指数,1000B=8仅仅是2的指数。
版本1 Java O(1)
public class Solution { public boolean isPowerOfFour(int num) { return num > 0 && ( num & num - 1 | num & 0x2AAAAAAA ) == 0 ; } }