【LeetCode】Power of Four 解题报告

Power of Four

[LeetCode]

https://leetcode.com/problems/power-of-four/

Total Accepted: 9305 Total Submissions: 28083 Difficulty: Easy

Question

Given an integer, write a function to determine if it is a power of 4.

Ways

和刚才那个是否为2的倍数好像。嗯。

方法一

我想的方法。很笨。

首先判断是否为2的倍数。n&(n-1)

然后在把8这些数给去掉。我想的是如果一个数为4的幂的话,那么它二进制中1后面一定有偶数个0。

所以这么写的:

public class Solution {
    public boolean isPowerOfFour(int num) {
        if(num<=0) return false;
        if(num==1) return true;
        if((num & (num-1))==0){
            while(num>0){
                num>>>=2;
                if(num==1){
                    return true;
                }
            }
        }
        return false;
    }
}

AC:2ms

效率凑活。

查了一下,发现还有更好的方法。就是判断二进制中1出现的位数是不是在奇数位。用0101 0101 ……来进行排除。16进制数为:0x55555555。

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

最起码代码比我的精简。嗯。

Date

2016/5/1 17:36:06

你可能感兴趣的:(LeetCode)