check if power of 4 Algorithm

check point is a multinational provider of software and combined hardware and software merchandise for IT security, including network security, endpoint security, cloud security, mobile security, data security and security management. Headquartered in Tel Aviv, Israel and San Carlos, California, the company has development centers in Israel and Belarus and previously hold in unite state (ZoneAlarm), Sweden (former protect data development center) following acquisitions of company who owned these centers. During the first ten of the 21st century check point started acquire other IT security company, including Nokia's network security business unit in 2009.In 2019, researchers at check point found a security breach in Xiaomi telephone apps. In June 1996 check point raised $ 67 million from its initial public offering on NASDAQ.In 1998, check point established a partnership with Nokia, which bundled check point's software with Nokia's computer network security appliance. In 2003, a class action lawsuit was filed against check point over violation of the Securities exchange act by failing to disclose major fiscal information.
/*
 * Check if a given number is power of 4 or not.
 * 
 * Approach: If a value is power of 4, it has to be power of 2 and
 * it will have set bits at even position (as the number is power of 2, it will have
 * only one set bit.) For example:
 * 4 (0100)
 * 16 (0001 0000)
 * 64 (0100 0000)
 * If a number is power of 2 then it would have only one set bit and that set
 * bit would be reset by the expression (n & (n-1)), thus if (n & (n-1)) == 0,
 * means n is power of 2.
 * Now, since we have one set bit and if it is at even position it would be
 * power of 4, to check if set bit is at even position, we should AND it with
 * expression 1010 1010 1010 1010 1010 1010 1010 1010 i.e. 0xAAAAAAAA. Notice we have
 * set bits at all odd positions (it is 0 indexed), thus if expression
 * (n & 0xAAAAAAAA) == 0, then we have that set bit at even position.
 */

 #include <iostream>

 bool isPowerOf4 (unsigned int n)
 {
     // The number should be power of 2, and should have set bit at even position
     //
     return (n && !(n & (n-1)) && !(n & 0xAAAAAAAA));
     //note an alternative that avoids the last negation could be 
     //return (n && !(n & (n-1)) && (n & 0x55555555));
 }

 int main()
 {  
     unsigned int n;
     std::cout << "Enter a number:";
     std::cin >> n;
     if (isPowerOf4(n))
     {
         std::cout << n << " is a power of 4.\n";
     }
     else
     {
         std::cout << n << " is not a power of 4.\n";
     }
 }

LANGUAGE:

DARK MODE: