342. Power of Four

判断一个数是不是4的幂。

First,greater than 0.Second,only have one ‘1’ bit in their binary notation,so we use x&(x-1) to delete the lowest ‘1’,and if then it becomes 0,it prove that there is only one ‘1’ bit.Third,the only ‘1’ bit should be locate at the odd location,for example,16.It’s binary is 00010000.So we can use ‘0x55555555’ to check if the ‘1’ bit is in the right place.

如果一个数是4的幂,那么它具备以下特点:

1. 大于0;

2. 这个数的二进制表达中只有一个“1”;

3. 这个唯一的“1”一定位于二进制表达中的奇数位,如100,10000,1分别位于第三位和第五位

由此,判断方法如下:

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 
    }0x55555555 二进制表示为0101 0101 0101 0101 0101 0101 0101 0101可以判断”1”的位置 

你可能感兴趣的:(leetcode,java基础)