題目:
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
思路:
(num&(num-1))==0
保證整個二進制中只有一個1;(num-1) % 3 == 0
保證1位於二進制中的偶數位上。
代碼實現:
class Solution {
public:
bool isPowerOfFour(int num) {
return num > 0 && (num&(num-1))==0 && (num-1) % 3 == 0;
}
};