Try   HackMD

342. 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

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

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

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