How to solve the Power of Four problem using loops in Java
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 or not.
Let’s understand with the help of two examples.
-
Suppose the number is . As , then our solution should tell the user that is the power of .
-
Now, suppose that the number is . As is not equal to , then our solution should tell the user that is not the power of .
Solution approach
To solve this problem, we will use the while loop and modulo () operator to determine whether a number is the power of or not. The time complexity for this solution will be and the space complexity will be .
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");elseSystem.out.println(x + " is not the power of 4");}}}
Explanation
-
In line 1, we imported the required package.
-
In line 2, we made a
Mainclass. -
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
whileloop. -
In lines 9 and 10, we have an
ifstatement 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 until it is divisible to remove all its factors and check if the remainder left is . Then, obviously the number is a power of .
-
In lines 17 to 20, we used an
if - elsestatement to check if the remainder left is , it is the power of 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.