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且还在这些位置上面的数都是满足条件的。
原文地址:https://www.cnblogs.com/linkstar/p/5926322.html