--- tags: leetcode --- # [342. Power of Four](https://leetcode.com/problems/power-of-four/) --- # Solution 1 ## The Key Idea for Solving This Coding Question Satisfy following three conditions 1. num is postive integer 2. num is power of 2. 3. This power of 2 is even power. ## C++ Code ```cpp= class Solution { public: bool isPowerOfFour(int num) { return num > 0 && // condition 1 (num & (num - 1)) == 0 && // condition 2 (0b01010101010101010101010101010101 & num) == num; // condition 3 } }; ``` ## Time Complexity $O(1)$ ## Space Complexity $O(1)$ <!-------------------------------> # Solution 2 ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= class Solution { public: bool isPowerOfFour(int n) { if (n <= 0) { return false; } while (n > 1) { if (n % 4) { return false; } n = n / 4; } return true; } }; ``` ## Time Complexity $O(1)$ ## Space Complexity $O(1)$ <!-------------------------------> # Solution 3 ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= class Solution { public: bool isPowerOfFour(int n) { if (n <= 0) { return false; } if (n == 1) { return true; } if (n % 4) { return false; } return isPowerOfFour(n / 4); } }; ``` ## Time Complexity $O(1)$ ## Space Complexity $O(1)$ # Miscellaneous <!-- # Test Cases ``` 16 ``` ``` 5 ``` ``` 2 ``` ``` 1 ``` ``` 4 ``` -->
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up