Skip to content

Latest commit

 

History

History
 
 

342. Power of Four

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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

Example 1:

Input: 16
Output: true

Example 2:

Input: 5
Output: false

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

Related Topics:
Bit Manipulation

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/power-of-four/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
    bool isPowerOfFour(int num) {
        return __builtin_popcount(num) == 1 && ((~0x55555555 & num) == 0);
    }
};

Or

// OJ: https://leetcode.com/problems/power-of-four/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
    bool isPowerOfFour(int num) {
        return num != INT_MIN && !(num & (num - 1)) && (num & 0x55555555);
    }
};