【LeetCode】342. Power of Four

题目

给定一个整数(带符号的32位),写一个函数来检查它是否为4的幂。
例1:

输入:16 
输出:true

例2:

输入:5 
输出:false

我写这篇博客倒不是因为这个题难,而是在讨论中看见最高票的两个代码,被惊到了,记录一下。代码如下

  • Java 1-line (cheating for the purpose of not using loops)
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 
    }
  • 1 line C++ solution without confusing bit manipulations
bool isPowerOfFour(int num) {
    return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
}

附录

其他特殊二进制位的整数
0xaaaaaaaa = 10101010101010101010101010101010 (偶数位为1,奇数位为0)
0x55555555 = 1010101010101010101010101010101 (偶数位为0,奇数位为1)
0x33333333 = 110011001100110011001100110011 (1和0每隔两位交替出现)
0xcccccccc = 11001100110011001100110011001100 (0和1每隔两位交替出现)
0x0f0f0f0f = 00001111000011110000111100001111 (1和0每隔四位交替出现)
0xf0f0f0f0 = 11110000111100001111000011110000 (0和1每隔四位交替出现)

参考目录

0x55555555,0xaaaaaaaa…等究竟是什么?

你可能感兴趣的:(LeetCode)