LeetCode 0342 - Power of Four

2021-08-11 11:20:03 浏览数 (3)

Power of Four

Desicription

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

Example 1:

代码语言:javascript复制
Input: 16
Output: true

Example 2:

代码语言:javascript复制
Input: 5
Output: false

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

Solution

代码语言:javascript复制
class Solution {
public:
    bool isPowerOfFour(int num) {
        return num > 0 && ((num & (num - 1)) == 0) && (num & 0x55555555) != 0;
    }
};

1 人点赞