Fork me on GitHub

leetcode342合理运用位操作判断4的幂

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?

我的解法极其垃圾,建议不要看。

public class Solution {
    public boolean isPowerOfFour(int num) {
        if(num == 0 || (num != 1 && num % 4 != 0))
            return false;
        else if(num == 1 || num == 4)
            return true;
        else
            return isPowerOfFour(num/4);
    }
}
复制代码

解释一下高手的解法。

public boolean isPowerOfFour(int num) {
        return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;
        //0x55555555 is to get rid of those power of 2 but not power of 4
        //so that the single 1 bit always appears at the odd position 
    }

要满足一个数是四的n阶指数如16,64这种,上面给出的解法意思就是要满足三个条件。

1、大于零

2、比它小1的数相与为0,简单的说,这个数的二进制表示的时候只能有一个1,其他的均为0

3、这个唯一的1必须正确的位置上面,

0x55555555 十六进制数,是01010101010101010101010101010101
和这个数相与如果结果不为那么1就在01010101010101010101010101010101的1的位置上面,只有一个1且还在这些位置上面的数都是满足条件的。
posted @   LinkinStar  阅读(272)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示