Power of Four - The Coding Shala

Home >> Programming >> Power of Four

 In this post, we will learn how to find if the Given number is Power of Four or not, and will implement its solution in Java.

Power of Four 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 == 4^x.

Example 1:
Input: n = 16
Output: true

Example 2:
Input: n = 5
Output: false

Example 3:
Input: n = 1
Output: true

Power of Four Java Solution

Approach 1

Using Bit Manipulation.

Java Program: 

class Solution {
    public boolean isPowerOfFour(int n) {
        if(n == 0) return false;
        for(int i=0; i<32; i=i+2) {
            if((n | (1 << i)) == (1 << i)) return true;
        }
        return false;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Longest Substring Without Repeating Characters Java Program - The Coding Shala

Anti Diagonals - The Coding Shala

First Missing Positive Solution - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala