LeetCode-342.Power of Four

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

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?

public bool IsPowerOfFour(int num)
    {
        return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) > 0;
    }
若一个整数是4的幂,则其二进制形式具有如下特点:
1. 最高位为1,其余位为0 =>  num & (num - 1) == 0
2. 0的个数为偶数 => num & 0x55555555 > 0

你可能感兴趣的:(LeetCode,leetcode)