LeetCode#342 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?

補充說明:

給定一個32位的整數,判斷這個數是否為4的幾次冪。

方案分析

  1. 首先看到這個題目能想到的是如何判斷一個數是不是2的幾次冪。
  2. 先分析2的幾次冪的問題,通常會采用位操作的方式:(num & (num -1)) == 0
  3. 分析是否是4的幾次冪,其實思想類似,但需要注意兩點:
  • 4的幾次冪關注的二進制位為偶數位,如1,3,5,7...31(從0開始)——對應的16進制為0x55555555;
  • 不能只局限關注偶數位的值,還需要借助2的幾次冪的問題確保其他位不為1.

python實現

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        return (num > 0) and ((num & (num-1)) == 0) and ((num & 0x55555555) == num)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容