Power of Four
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?
4的幂次方 二进制里只有1个1
判断二进制里有没有1个1 用n & (n-1)== 0
1 bool isPowerOfFour(int num) { 2 if(num <= 0) return false; 3 if(num & (num - 1)) return false; 4 if(num & 0x55555555) return true; // 再将不是 4 的 N 次方的数字去掉 5 return false; 6 }