342. Power of Four

Description

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

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

Solution

在判断2^x的基础上再使用一个mask就好啦。

Bit operation, time O(1), space O(1)

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

你可能感兴趣的:(342. Power of Four)