How to solve the Power of Three problem using Java
Problem statement
The problem statement is as follows:
Given an integer , 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 such that .
Below are some examples:
- Suppose that the input . The output will be
trueas 27 is a power of three, i.e., . - Similarly, if the input . The output will be
falseas 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.");elseSystem.out.println(n + " is not a Power of Three.");}}
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
falsebecause 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 returnfalse. - From lines 13 to 19, we create the
main()function, call theisPowerOfThree()function, and print the corresponding message.
In this way, we can solve the Power of Three problem.