Related Tags

java
interview
communitycreator

How to solve the Power of Three problem using Java

Harsh Jain

Problem statement

The problem statement is as follows:

Given an integer $n$, return true if it is a power of three. Otherwise, return false. An integer n is a power of three if there exists an integer $x$ such that $n == 3^x$.

Below are some examples:

• Suppose that the input $n = 27$. The output will be true as 27 is a power of three, i.e., $3^{3} = 27$.
• Similarly, if the input $n = 2$. The output will be false as 2 is not a power of three.

Solution approach

Here we will create a function, isPowerOfThree(), which will take an input integer number as a parameter and return true or false depending on whether the number is a power of three.

class Solution {
public static boolean isPowerOfThree(int n) {
if(n<3)
return false;

while(n%3==0)
{
n/=3;
}

return n==1;
}
public static void main(String[] args){
int n = 27;
if (isPowerOfThree(n))
System.out.println(n + " is a Power of Three.");
else
System.out.println(n + " is not a Power of Three.");
}
}

Solution of Power of Three Problem

Explanation:

• In line 2, we initiate the function isPowerOfThree(int n), which will take an integer as input.
• In line 3, there is a case that if the number is less than 3, then it will return false because it won’t be a power of 3 then.
• In lines 6 to 9, we loop and decrease by dividing the integer by 3. We do this until the number is perfectly divided by 3.
• In line 11, if the number remains 1, then we will return true. Otherwise, we will return false.
• From lines 13 to 19, we create the main() function, call the isPowerOfThree() function, and print the corresponding message.

In this way, we can solve the Power of Three problem.

RELATED TAGS

java
interview
communitycreator

CONTRIBUTOR

Harsh Jain
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time