Find whether a given number is a power of 4 or not | C ++ program to check if given number is power of 4 or not ; Function to check if x is power of 4 ; Check if there is only one bit set in n ; count 0 bits before set bit ; If count is even then return true else false ; If there are more than 1 bit set then n is not a power of 4 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfFour ( unsigned int n ) { int count = 0 ; if ( n && ! ( n & ( n - 1 ) ) ) { while ( n > 1 ) { n >>= 1 ; count += 1 ; } return ( count % 2 == 0 ) ? 1 : 0 ; } return 0 ; } int main ( ) { int test_no = 64 ; if ( isPowerOfFour ( test_no ) ) cout << test_no << " ▁ is ▁ a ▁ power ▁ of ▁ 4" ; else cout << test_no << " ▁ is ▁ not ▁ a ▁ power ▁ of ▁ 4" ; }