leetcode 53,[LeetCode] 342. Power of Four(位操作)

 2023-11-19 阅读 30 评论 0

摘要:傳送門 Description 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? 思路 題意:不

傳送門

Description

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?

思路

題意:不使用循環和遞歸,求一個數是否是4的冪次。

題解:我們知道凡是4的冪次,那么其二進制位肯定只有一個1其余都是0,并且可以發現規律,從4的零次冪開始列舉,可以發現與上一個冪次相比,隔了一個0,也就是將4的冪次的二進制位寫在一起,呈現出...0101...的形式,因此根據 ?num & (num - 1)可以判定二進制位是否只有一個1,然后再與十六進制的55555555相與即可判斷是否有4的冪次的表現形式,因為十六進制的5的表現形式正好是0101。

leetcode 53、?

class Solution {
public://3msbool isPowerOfFour(int num) {return !(num & (num - 1)) && (num & 0x55555555);}
};

  

轉載于:https://www.cnblogs.com/ZhaoxiCheung/p/7400404.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/181544.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息