leetcode 342. Power of Four 判断一个数是否为4的幂

来源:互联网 发布:算法 第四版 微盘 编辑:程序博客网 时间:2024/05/22 08:29

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?

这到题和Power of two类似,如果不能用递归循环做,就使用位操作。1个数是2的幂肯定是4的幂,但反过来不成立,4的幂只能是奇数位为1,而2的幂只有有一个位置为1就行。

所以先判断是否为2的幂,然后通过与.0X55555555(....1010101)进行&操作,保留奇数位,判断是否改变。

    public boolean isPowerOfFour(int num) {        if(num<=0)            return false;        return (num & num-1)==0 && (num&0x55555555)==num;                    }


1 0