Power of Four(Difficulty: Easy)

題目:

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.spa

Example:
Given num = 16, return true. Given num = 5, return false.code

實現:

1 class Solution { 2 public: 3     bool isPowerOfFour(int num) { 4         return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num); 5  } 6 };

分析:

(num & (num - 1)) == 0 判斷這個數是否是2的倍數,(num & 0x55555555) == num 判斷是否是4的倍數。0x55555555就是二進制數上奇數位上爲1.blog

相關文章
相關標籤/搜索