首页 leetcode

题目描述

给定一个整数,写一个函数来判断它是否是 4 的幂次方。如果是,返回 true ;否则,返回 false 。

整数 n 是 4 的幂次方需满足:存在整数 x 使得 n == 4x

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/power-of-four
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

提示:

  • -231 <= n <= 231 - 1

输入样例:

n = 16
n = 5
n = 1

输出样例:

true
false
true
ac代码
class Solution {
public:
    bool isPowerOfFour(int n) {
        bool a = false;
        while (n > 0 && (n % 4 == 0 || n == 1) ) {
            n /= 4;
            if (n == 1 || n == 0) {
                a = true;
                break;
            }
        }
        return a;
    }
};
心得:

4 / 4 =1

1 / 4 = 0

$$4^x\equiv(3+1)^x\equiv1^x\equiv1(\mod3)$$

// 评论区大佬的代码
//0x5 = 0101b
bool isPowerOfFour(int num) {
    if (num < 0 || num & (num-1)){//check(is or not) a power of 2.
        return false;
    }
    return num & 0x55555555;//check 1 on odd bits  // num & 0x55555555 也可以换成 num % 3 == 1
}
// 暴力出奇迹
bool isPowerOfFour(int num)
{
    // return num == 1 || num == 4 || num ==16 || num == 64 || num == 256 || num == 1024 || num == 4096 || num == 16384 || num == 65536 || num == 262144 || num == 1048576 || num == 4194304 || num == 16777216 || num == 67108864 || num == 268435456 || num == 1073741824;
    return (num == 0x00000001) ||
           (num == 0x00000004) ||
           (num == 0x00000010) ||
           (num == 0x00000040) ||
           (num == 0x00000100) ||
           (num == 0x00000400) ||
           (num == 0x00001000) ||
           (num == 0x00004000) ||
           (num == 0x00010000) || 
           (num == 0x00040000) ||
           (num == 0x00100000) ||
           (num == 0x00400000) ||
           (num == 0x01000000) ||
           (num == 0x04000000) ||
           (num == 0x10000000) ||
           (num == 0x40000000) ;
}



文章评论

目录