Power of Four in C++


Suppose we have an integer; we have to check whether that is a power of 4 or not.

So, if the input is like 16, then the output will be True.

To solve this, we will follow these steps −

  • if num < 0, then −

    • return false

  • if num & (num - 1) is non-zero, then −

    • return false

  • if (num & 01010101010101010101010101010101) is zero, then −

    • return false

  • return true

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool isPowerOfFour(int num){
      if (num < 0)
         return false;
      if (num & (num - 1))
         return false;
      if (!(num & 0x55555555))
         return false;
      return true;
   }
};
main(){
   Solution ob;
   cout << (ob.isPowerOfFour(64));
}

Input

64

Output

1

Updated on: 10-Jun-2020

98 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements