[Leetcode学习-java]Power of Four(判断4的指数)

问题:

难度:easy

网址链接:https://leetcode.com/problems/power-of-four/

说明:

水题,输入一个N正整数,求是否是4^N的数,之前做过了2的指数,方法可以类似。

相关算法:

https://blog.csdn.net/qq_28033719/article/details/106528987 Power of Two(判断2的指数)

输入案例:

Example 1:
Input: 16
Output: true

Example 2:
Input: 5
Output: false

我的代码:

对于正整数,因为2指数是 (n & (n - 1)) == 0,所以 符合 2指数条件下,4的话可以发现:

4 - 1 =  0 1 1, 16 - 1 = 0 1 1 1 1,后面跟着 偶数个 1,也就是 3 * N (N 个 0 1 1),所以 (4^N - 1) % 3 == 0 就行了。

class Solution {
    public boolean isPowerOfFour(int num) {
        return num >= 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
    }
}

其它代码:

当然 n & 0x5555 是最标准的,因为 5 = 0 1 0 1,刚好都隔了一个 0,4的次方也是 4^0 = 1; 4 ^ 1 = 1 0 0;4 ^ 2 = 1 0 0 0 0。

class Solution {
    public boolean isPowerOfFour(int num) {
        return num > 0 &&
            (num & (num - 1)) == 0 &&
            (num & 0x55555555) != 0;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/107806740