Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

342. Power of Four 🌟

Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x.

General Solution for any power

Code

class Solution {
public:
    bool isPowerOfFour(int n) {
        if(n>1)while(n%4==0) n/=4;
        return n==1;
    }
};

Bitwise Solution

Code

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

MUST READ