Leetcode 326. Power of Three
[Easy]
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
Example 2:
Input: n = 0
Output: false
Example 3:
Input: n = 9
Output: true
Example 4:
Input: n = 45
Output: false
Follow up: Could you solve it without loops/recursion?
[Gary- recursion]
First answer in Java.
Think:
- check 0 and 1 corner case.
- recursion loop n and make sure there is no MOD exist and become 1 at the end
- can add another line to count how many times it loops
Another recursion answer using two lines:
Basically, it’s the same method but more short.
[Second- brute force Java]
Using HashSet or Array to list all the possible ture answer.
notes: Arrays.binarySearch will return the index of searching result. If no exist in the array, it will return -1.
use array as list in Hashset, and check if result n contains in hashset.
[Third- using Log10, Log3]
notes: have to put log10, instead of log. There will be minor error. And this solution is math solution.