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:
true
as 27 is a power of three, i.e., .false
as 2 is not a power of three.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.");}}
isPowerOfThree(int n)
, which will take an integer as input.false
because it won’t be a power of 3 then.true
. Otherwise, we will return false
.main()
function, call the isPowerOfThree()
function, and print the corresponding message.In this way, we can solve the Power of Three problem.