Power of Four – Leetcode Solution

In this post, we are going to solve the 342. Power of Four problem of Leetcode. This problem 342. Power of Four is a Leetcode easy level problem. Let’s see the code, 342. Power of Four – Leetcode Solution.

Problem

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

Now, let’s see the code of 342. Power of Four – Leetcode Solution.

Power of Four – Leetcode Solution

342. Power of Four – Solution in Java

class Solution {
    
    public boolean isPowerOfTwo(int n){
        return ( (n > 0) && ( ( n & (n-1)) == 0 )  );
    }
    public boolean isPowerOfFour(int n) {
        return (isPowerOfTwo(n) && (n & 0x55555555)!=0);
    }
}

342. Power of Four – Solution in C++

class Solution {
public:
    bool isPowerOfTwo(int n){
        return ( (n > 0) and ( ( n & (n-1)) == 0 )  );
    }
    bool isPowerOfFour(int n) {
        return (isPowerOfTwo(n) and (n & 0x55555555)!=0);
    }
};

342. Power of Four – Solution in Python

class Solution:
    def isPowerOfFour(self, num):
        return num != 0 and num &(num-1) == 0 and num & 0x55555555== num
        

Note: This problem 342. Power of Four is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published.