Given an integer (signed 32 bits), write a function to check whether it is a power of 4.git
Example 1:github
Input: 16
Output: true
Example 2:函數
Input: 5
Output: false
Follow up: Could you solve it without loops/recursion?oop
給定一個整數 (32 位有符號整數),請編寫一個函數來判斷它是不是 4 的冪次方。ui
示例 1:code
輸入: 16
輸出: true
示例 2:遞歸
輸入: 5
輸出: false
進階:
你能不使用循環或者遞歸來完成本題嗎?ip
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-04-08 16:58:04 # @Last Modified by: 何睿 # @Last Modified time: 2019-04-08 17:11:49 class Solution: def isPowerOfFour(self, num: 'int') -> 'bool': # num 數字不爲零 # num 的二級制只有一個 1 # num 中 1 的位置出如今第 1 位,或第 3 位,或第5 ... 位 return num != 0 and num & ( num - 1) == 0 and num & 0b1010101010101010101010101010101 == num