LeetCode 342. Power of Four

Description

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

思路

  • 一個數如果 4 的冪次方,那麼這個數的二進制表示只有一個 1。
  • 而且這個數的1 出如今(從右往左) 第 1,或 3,或 5 ,或 7 ... 位。
  • 一個數 num 只有一個 1 那麼,num 和 num -1 與運算結果爲 0。
  • 1 出如今奇數位,那麼此數與 1010101010101010101010101010101 與運算爲 num 自己。
# -*- 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

源代碼文件在 這裏
©本文首發於 何睿的博客 ,歡迎轉載,轉載需保留 文章來源 ,做者信息和本聲明.utf-8

相關文章
相關標籤/搜索