Related Tags

java
communitycreator

# How to solve the Power of Four problem using loops in Java

Harsh Jain

In this shot, we will solve an interview problem from Leetcode named Power of Four. In this problem, we will learn how to determine whether a number is a power of $4$ or not.

Let’s understand with the help of two examples.

1. Suppose the number is $16$. As $16 =$ $4^2$ , then our solution should tell the user that $16$ is the power of $4$.

2. Now, suppose that the number is $18$. As $18$ is not equal to $4^n$, then our solution should tell the user that $18$ is not the power of $4$.

### Solution approach

To solve this problem, we will use the while loop and modulo ($%$) operator to determine whether a number is the power of $4$ or not. The time complexity for this solution will be $O(log_{4} \space N)$ and the space complexity will be $O(1)$.

### Code

Let’s have a look at the code:

import java.util.*;
class Main
{
public static void main(String[] args)
{
int n = 16;
int x = n;

if (n == 0)
System.out.println(x + " is not the power of 4");

else {
while (n % 4 == 0)
n = n / 4;

if(n == 1)
System.out.println(x + " is the power of 4");
else
System.out.println(x + " is not the power of 4");
}

}
}
Solution of the Power of Four problem

### Explanation

• In line 1, we imported the required package.

• In line 2, we made a Main class.

• In line 4, we made a main() function.

• In line 6, we defined the number that we want to check.

• In line 7, we stored the value of that number in a separate variable, as the original variable’s value may change when we perform the division inside the while loop.

• In lines 9 and 10, we have an if statement to check whether the number is positive or not, and if not, a message is displayed.

• In line 13, we looped and divided the number by $4$ until it is divisible to remove all its factors and check if the remainder left is $1$. Then, obviously the number is a power of $4$.

• In lines 17 to 20, we used an if - else statement to check if the remainder left is $1$, it is the power of $4$ otherwise not. Thus, the result message is displayed accordingly.

So, in this way, we can solve the Power of Four problem using loops in Java.

RELATED TAGS

java
communitycreator

CONTRIBUTOR

Harsh Jain
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time