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 }