Power of Three Java Solution| Leetcode 326 Java

Let us see what is the problem statement for Power of Three(326 leetcode)

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 == 3x.

Example 1: Input: n = 27 Output: true Explanation: 27 = 33

Solution 1: Brute force

To solve this problem we employ a brute force approach where we divide the given input number by 3 until we get a number which is less or equal to 1. If during process remainder is not zero that means it not a power of 3

For example:

If number is n=12,

Step 1: 12/3=4, 12%3=0 Remainder=0

Step 2: 4/3=1, 4%3=1 Remainder=1 –> exit here which means 12 is not power of three

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    public boolean isPowerOfThree(int n) {
        
        if(n<=0)
            return false;

        while(n>1){
            if(n%3!=0){
                return false;
            }
            n= n/3;
        }

        return true;
        
    }
}

Solution 2: Recursion approach

By applying the same logic we can solve the problem by using recursion.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public boolean isPowerOfThree(int n) {
        
        if(n==0) return false;
         if(n==1) return true;
         if(n%3!=0)
             return false;
         return isPowerOfThree(n/3);
        
    }
}

Recursion approach provided above if much faster than Brute force approach!