Algorithm


Problem Name: 342. Power of Four

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4x.

 

Example 1:

Input: n = 16
Output: true

Example 2:

Input: n = 5
Output: false

Example 3:

Input: n = 1
Output: true

 

Constraints:

  • -231 <= n <= 231 - 1

Code Examples

#1 Code Example with C Programming

Code - C Programming


bool isPowerOfFour(int num) {
    // one bit only and has to be on 0101 0101 0101 0101
    return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 16

Output

x
+
cmd
true

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
  public boolean isPowerOfFour(int n) {
    long left = 0;
    long right = n / 2 + 1;
    while (left  < = right) {
      long mid = (left + right) / 2;
      long pow = (long) (Math.pow(4, mid));
      if (pow == ((long) n)) {
        return true;
      }
      if (pow > ((long) n)) {
        right = mid - 1;
      } else {
        left = mid + 1;
      }
    }
    return false;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 16

Output

x
+
cmd
true

#3 Code Example with Javascript Programming

Code - Javascript Programming


const isPowerOfFour = function(num) {
  if (num === 1) { return true; }
  let f = 4;
  while (f  < = num) {
      if (f === num) {
          return true;
      }
      f *= 4;
  }
  return false;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 5

Output

x
+
cmd
false

#4 Code Example with Python Programming

Code - Python Programming


class Solution:
    def isPowerOfFour(self, num: int) -> bool:
        if num < 0:
            return False
        i = 1
        while i < num:
            i = i * 4
        return i == num
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 5

Output

x
+
cmd
false

#5 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _0342_PowerOfFour
    {
        public bool IsPowerOfFour(int num)
        {
            return num > 0 && ((num & (num - 1)) == 0) && ((num & 0xaaaaaaaa) == 0);
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 1

Output

x
+
cmd
true
Advertisements

Demonstration


Previous
#341 Leetcode Flatten Nested List Iterator Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#343 Leetcode Integer Break Solution in C, C++, Java, JavaScript, Python, C# Leetcode