Trusted answers to developer questions
Trusted Answers to Developer Questions

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 44 or not.

Let’s understand with the help of two examples.

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

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

Solution approach

To solve this problem, we will use the while loop and modulo (%) operator to determine whether a number is the power of 44 or not. The time complexity for this solution will be O(log4 N)O(log_{4} \space N) and the space complexity will be O(1)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 44 until it is divisible to remove all its factors and check if the remainder left is 11. Then, obviously the number is a power of 44.

  • In lines 17 to 20, we used an if - else statement to check if the remainder left is 11, it is the power of 44 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
RELATED COURSES

View all Courses

Keep Exploring