Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

通过4, 16, 64找规律,1. num是power of two, 即一个1之后所有位都是0, 2, 0的个数是偶数

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

Leave a comment