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
|
|
Solution 2: Recursion approach
By applying the same logic we can solve the problem by using recursion.
|
|
Recursion approach provided above if much faster than Brute force approach!