
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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
Advertisements